Edit on GitHub

Expressions

Every AST node in SQLGlot is represented by a subclass of Expression.

This module contains the implementation of all supported Expression types. Additionally, it exposes a number of helper functions, which are mainly used to programmatically build SQL expressions, such as sqlglot.expressions.select.


   1"""
   2## Expressions
   3
   4Every AST node in SQLGlot is represented by a subclass of `Expression`.
   5
   6This module contains the implementation of all supported `Expression` types. Additionally,
   7it exposes a number of helper functions, which are mainly used to programmatically build
   8SQL expressions, such as `sqlglot.expressions.select`.
   9
  10----
  11"""
  12
  13from __future__ import annotations
  14
  15import datetime
  16import math
  17import numbers
  18import re
  19import typing as t
  20from collections import deque
  21from copy import deepcopy
  22from enum import auto
  23
  24from sqlglot.errors import ParseError
  25from sqlglot.helper import (
  26    AutoName,
  27    camel_to_snake_case,
  28    ensure_collection,
  29    ensure_list,
  30    seq_get,
  31    split_num_words,
  32    subclasses,
  33)
  34from sqlglot.tokens import Token
  35
  36if t.TYPE_CHECKING:
  37    from sqlglot.dialects.dialect import DialectType
  38
  39E = t.TypeVar("E", bound="Expression")
  40
  41
  42class _Expression(type):
  43    def __new__(cls, clsname, bases, attrs):
  44        klass = super().__new__(cls, clsname, bases, attrs)
  45
  46        # When an Expression class is created, its key is automatically set to be
  47        # the lowercase version of the class' name.
  48        klass.key = clsname.lower()
  49
  50        # This is so that docstrings are not inherited in pdoc
  51        klass.__doc__ = klass.__doc__ or ""
  52
  53        return klass
  54
  55
  56class Expression(metaclass=_Expression):
  57    """
  58    The base class for all expressions in a syntax tree. Each Expression encapsulates any necessary
  59    context, such as its child expressions, their names (arg keys), and whether a given child expression
  60    is optional or not.
  61
  62    Attributes:
  63        key: a unique key for each class in the Expression hierarchy. This is useful for hashing
  64            and representing expressions as strings.
  65        arg_types: determines what arguments (child nodes) are supported by an expression. It
  66            maps arg keys to booleans that indicate whether the corresponding args are optional.
  67        parent: a reference to the parent expression (or None, in case of root expressions).
  68        arg_key: the arg key an expression is associated with, i.e. the name its parent expression
  69            uses to refer to it.
  70        comments: a list of comments that are associated with a given expression. This is used in
  71            order to preserve comments when transpiling SQL code.
  72        _type: the `sqlglot.expressions.DataType` type of an expression. This is inferred by the
  73            optimizer, in order to enable some transformations that require type information.
  74
  75    Example:
  76        >>> class Foo(Expression):
  77        ...     arg_types = {"this": True, "expression": False}
  78
  79        The above definition informs us that Foo is an Expression that requires an argument called
  80        "this" and may also optionally receive an argument called "expression".
  81
  82    Args:
  83        args: a mapping used for retrieving the arguments of an expression, given their arg keys.
  84    """
  85
  86    key = "expression"
  87    arg_types = {"this": True}
  88    __slots__ = ("args", "parent", "arg_key", "comments", "_type", "_meta", "_hash")
  89
  90    def __init__(self, **args: t.Any):
  91        self.args: t.Dict[str, t.Any] = args
  92        self.parent: t.Optional[Expression] = None
  93        self.arg_key: t.Optional[str] = None
  94        self.comments: t.Optional[t.List[str]] = None
  95        self._type: t.Optional[DataType] = None
  96        self._meta: t.Optional[t.Dict[str, t.Any]] = None
  97        self._hash: t.Optional[int] = None
  98
  99        for arg_key, value in self.args.items():
 100            self._set_parent(arg_key, value)
 101
 102    def __eq__(self, other) -> bool:
 103        return type(self) is type(other) and hash(self) == hash(other)
 104
 105    @property
 106    def hashable_args(self) -> t.Any:
 107        args = (self.args.get(k) for k in self.arg_types)
 108
 109        return tuple(
 110            (tuple(_norm_arg(a) for a in arg) if arg else None)
 111            if type(arg) is list
 112            else (_norm_arg(arg) if arg is not None and arg is not False else None)
 113            for arg in args
 114        )
 115
 116    def __hash__(self) -> int:
 117        if self._hash is not None:
 118            return self._hash
 119
 120        return hash((self.__class__, self.hashable_args))
 121
 122    @property
 123    def this(self):
 124        """
 125        Retrieves the argument with key "this".
 126        """
 127        return self.args.get("this")
 128
 129    @property
 130    def expression(self):
 131        """
 132        Retrieves the argument with key "expression".
 133        """
 134        return self.args.get("expression")
 135
 136    @property
 137    def expressions(self):
 138        """
 139        Retrieves the argument with key "expressions".
 140        """
 141        return self.args.get("expressions") or []
 142
 143    def text(self, key) -> str:
 144        """
 145        Returns a textual representation of the argument corresponding to "key". This can only be used
 146        for args that are strings or leaf Expression instances, such as identifiers and literals.
 147        """
 148        field = self.args.get(key)
 149        if isinstance(field, str):
 150            return field
 151        if isinstance(field, (Identifier, Literal, Var)):
 152            return field.this
 153        if isinstance(field, (Star, Null)):
 154            return field.name
 155        return ""
 156
 157    @property
 158    def is_string(self) -> bool:
 159        """
 160        Checks whether a Literal expression is a string.
 161        """
 162        return isinstance(self, Literal) and self.args["is_string"]
 163
 164    @property
 165    def is_number(self) -> bool:
 166        """
 167        Checks whether a Literal expression is a number.
 168        """
 169        return isinstance(self, Literal) and not self.args["is_string"]
 170
 171    @property
 172    def is_int(self) -> bool:
 173        """
 174        Checks whether a Literal expression is an integer.
 175        """
 176        if self.is_number:
 177            try:
 178                int(self.name)
 179                return True
 180            except ValueError:
 181                pass
 182        return False
 183
 184    @property
 185    def is_star(self) -> bool:
 186        """Checks whether an expression is a star."""
 187        return isinstance(self, Star) or (isinstance(self, Column) and isinstance(self.this, Star))
 188
 189    @property
 190    def alias(self) -> str:
 191        """
 192        Returns the alias of the expression, or an empty string if it's not aliased.
 193        """
 194        if isinstance(self.args.get("alias"), TableAlias):
 195            return self.args["alias"].name
 196        return self.text("alias")
 197
 198    @property
 199    def name(self) -> str:
 200        return self.text("this")
 201
 202    @property
 203    def alias_or_name(self):
 204        return self.alias or self.name
 205
 206    @property
 207    def output_name(self):
 208        """
 209        Name of the output column if this expression is a selection.
 210
 211        If the Expression has no output name, an empty string is returned.
 212
 213        Example:
 214            >>> from sqlglot import parse_one
 215            >>> parse_one("SELECT a").expressions[0].output_name
 216            'a'
 217            >>> parse_one("SELECT b AS c").expressions[0].output_name
 218            'c'
 219            >>> parse_one("SELECT 1 + 2").expressions[0].output_name
 220            ''
 221        """
 222        return ""
 223
 224    @property
 225    def type(self) -> t.Optional[DataType]:
 226        return self._type
 227
 228    @type.setter
 229    def type(self, dtype: t.Optional[DataType | DataType.Type | str]) -> None:
 230        if dtype and not isinstance(dtype, DataType):
 231            dtype = DataType.build(dtype)
 232        self._type = dtype  # type: ignore
 233
 234    @property
 235    def meta(self) -> t.Dict[str, t.Any]:
 236        if self._meta is None:
 237            self._meta = {}
 238        return self._meta
 239
 240    def __deepcopy__(self, memo):
 241        copy = self.__class__(**deepcopy(self.args))
 242        if self.comments is not None:
 243            copy.comments = deepcopy(self.comments)
 244
 245        if self._type is not None:
 246            copy._type = self._type.copy()
 247
 248        if self._meta is not None:
 249            copy._meta = deepcopy(self._meta)
 250
 251        return copy
 252
 253    def copy(self):
 254        """
 255        Returns a deep copy of the expression.
 256        """
 257        new = deepcopy(self)
 258        new.parent = self.parent
 259        return new
 260
 261    def add_comments(self, comments: t.Optional[t.List[str]]) -> None:
 262        if self.comments is None:
 263            self.comments = []
 264        if comments:
 265            self.comments.extend(comments)
 266
 267    def append(self, arg_key, value):
 268        """
 269        Appends value to arg_key if it's a list or sets it as a new list.
 270
 271        Args:
 272            arg_key (str): name of the list expression arg
 273            value (Any): value to append to the list
 274        """
 275        if not isinstance(self.args.get(arg_key), list):
 276            self.args[arg_key] = []
 277        self.args[arg_key].append(value)
 278        self._set_parent(arg_key, value)
 279
 280    def set(self, arg_key, value):
 281        """
 282        Sets `arg_key` to `value`.
 283
 284        Args:
 285            arg_key (str): name of the expression arg.
 286            value: value to set the arg to.
 287        """
 288        self.args[arg_key] = value
 289        self._set_parent(arg_key, value)
 290
 291    def _set_parent(self, arg_key, value):
 292        if hasattr(value, "parent"):
 293            value.parent = self
 294            value.arg_key = arg_key
 295        elif type(value) is list:
 296            for v in value:
 297                if hasattr(v, "parent"):
 298                    v.parent = self
 299                    v.arg_key = arg_key
 300
 301    @property
 302    def depth(self):
 303        """
 304        Returns the depth of this tree.
 305        """
 306        if self.parent:
 307            return self.parent.depth + 1
 308        return 0
 309
 310    def iter_expressions(self) -> t.Iterator[t.Tuple[str, Expression]]:
 311        """Yields the key and expression for all arguments, exploding list args."""
 312        for k, vs in self.args.items():
 313            if type(vs) is list:
 314                for v in vs:
 315                    if hasattr(v, "parent"):
 316                        yield k, v
 317            else:
 318                if hasattr(vs, "parent"):
 319                    yield k, vs
 320
 321    def find(self, *expression_types: t.Type[E], bfs=True) -> E | None:
 322        """
 323        Returns the first node in this tree which matches at least one of
 324        the specified types.
 325
 326        Args:
 327            expression_types: the expression type(s) to match.
 328
 329        Returns:
 330            The node which matches the criteria or None if no such node was found.
 331        """
 332        return next(self.find_all(*expression_types, bfs=bfs), None)
 333
 334    def find_all(self, *expression_types: t.Type[E], bfs=True) -> t.Iterator[E]:
 335        """
 336        Returns a generator object which visits all nodes in this tree and only
 337        yields those that match at least one of the specified expression types.
 338
 339        Args:
 340            expression_types: the expression type(s) to match.
 341
 342        Returns:
 343            The generator object.
 344        """
 345        for expression, *_ in self.walk(bfs=bfs):
 346            if isinstance(expression, expression_types):
 347                yield expression
 348
 349    def find_ancestor(self, *expression_types: t.Type[E]) -> E | None:
 350        """
 351        Returns a nearest parent matching expression_types.
 352
 353        Args:
 354            expression_types: the expression type(s) to match.
 355
 356        Returns:
 357            The parent node.
 358        """
 359        ancestor = self.parent
 360        while ancestor and not isinstance(ancestor, expression_types):
 361            ancestor = ancestor.parent
 362        return t.cast(E, ancestor)
 363
 364    @property
 365    def parent_select(self):
 366        """
 367        Returns the parent select statement.
 368        """
 369        return self.find_ancestor(Select)
 370
 371    @property
 372    def same_parent(self):
 373        """Returns if the parent is the same class as itself."""
 374        return type(self.parent) is self.__class__
 375
 376    def root(self) -> Expression:
 377        """
 378        Returns the root expression of this tree.
 379        """
 380        expression = self
 381        while expression.parent:
 382            expression = expression.parent
 383        return expression
 384
 385    def walk(self, bfs=True, prune=None):
 386        """
 387        Returns a generator object which visits all nodes in this tree.
 388
 389        Args:
 390            bfs (bool): if set to True the BFS traversal order will be applied,
 391                otherwise the DFS traversal will be used instead.
 392            prune ((node, parent, arg_key) -> bool): callable that returns True if
 393                the generator should stop traversing this branch of the tree.
 394
 395        Returns:
 396            the generator object.
 397        """
 398        if bfs:
 399            yield from self.bfs(prune=prune)
 400        else:
 401            yield from self.dfs(prune=prune)
 402
 403    def dfs(self, parent=None, key=None, prune=None):
 404        """
 405        Returns a generator object which visits all nodes in this tree in
 406        the DFS (Depth-first) order.
 407
 408        Returns:
 409            The generator object.
 410        """
 411        parent = parent or self.parent
 412        yield self, parent, key
 413        if prune and prune(self, parent, key):
 414            return
 415
 416        for k, v in self.iter_expressions():
 417            yield from v.dfs(self, k, prune)
 418
 419    def bfs(self, prune=None):
 420        """
 421        Returns a generator object which visits all nodes in this tree in
 422        the BFS (Breadth-first) order.
 423
 424        Returns:
 425            The generator object.
 426        """
 427        queue = deque([(self, self.parent, None)])
 428
 429        while queue:
 430            item, parent, key = queue.popleft()
 431
 432            yield item, parent, key
 433            if prune and prune(item, parent, key):
 434                continue
 435
 436            for k, v in item.iter_expressions():
 437                queue.append((v, item, k))
 438
 439    def unnest(self):
 440        """
 441        Returns the first non parenthesis child or self.
 442        """
 443        expression = self
 444        while type(expression) is Paren:
 445            expression = expression.this
 446        return expression
 447
 448    def unalias(self):
 449        """
 450        Returns the inner expression if this is an Alias.
 451        """
 452        if isinstance(self, Alias):
 453            return self.this
 454        return self
 455
 456    def unnest_operands(self):
 457        """
 458        Returns unnested operands as a tuple.
 459        """
 460        return tuple(arg.unnest() for _, arg in self.iter_expressions())
 461
 462    def flatten(self, unnest=True):
 463        """
 464        Returns a generator which yields child nodes who's parents are the same class.
 465
 466        A AND B AND C -> [A, B, C]
 467        """
 468        for node, _, _ in self.dfs(prune=lambda n, p, *_: p and not type(n) is self.__class__):
 469            if not type(node) is self.__class__:
 470                yield node.unnest() if unnest else node
 471
 472    def __str__(self):
 473        return self.sql()
 474
 475    def __repr__(self):
 476        return self._to_s()
 477
 478    def sql(self, dialect: DialectType = None, **opts) -> str:
 479        """
 480        Returns SQL string representation of this tree.
 481
 482        Args:
 483            dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
 484            opts: other `sqlglot.generator.Generator` options.
 485
 486        Returns:
 487            The SQL string.
 488        """
 489        from sqlglot.dialects import Dialect
 490
 491        return Dialect.get_or_raise(dialect)().generate(self, **opts)
 492
 493    def _to_s(self, hide_missing: bool = True, level: int = 0) -> str:
 494        indent = "" if not level else "\n"
 495        indent += "".join(["  "] * level)
 496        left = f"({self.key.upper()} "
 497
 498        args: t.Dict[str, t.Any] = {
 499            k: ", ".join(
 500                v._to_s(hide_missing=hide_missing, level=level + 1)
 501                if hasattr(v, "_to_s")
 502                else str(v)
 503                for v in ensure_list(vs)
 504                if v is not None
 505            )
 506            for k, vs in self.args.items()
 507        }
 508        args["comments"] = self.comments
 509        args["type"] = self.type
 510        args = {k: v for k, v in args.items() if v or not hide_missing}
 511
 512        right = ", ".join(f"{k}: {v}" for k, v in args.items())
 513        right += ")"
 514
 515        return indent + left + right
 516
 517    def transform(self, fun, *args, copy=True, **kwargs):
 518        """
 519        Recursively visits all tree nodes (excluding already transformed ones)
 520        and applies the given transformation function to each node.
 521
 522        Args:
 523            fun (function): a function which takes a node as an argument and returns a
 524                new transformed node or the same node without modifications. If the function
 525                returns None, then the corresponding node will be removed from the syntax tree.
 526            copy (bool): if set to True a new tree instance is constructed, otherwise the tree is
 527                modified in place.
 528
 529        Returns:
 530            The transformed tree.
 531        """
 532        node = self.copy() if copy else self
 533        new_node = fun(node, *args, **kwargs)
 534
 535        if new_node is None or not isinstance(new_node, Expression):
 536            return new_node
 537        if new_node is not node:
 538            new_node.parent = node.parent
 539            return new_node
 540
 541        replace_children(new_node, lambda child: child.transform(fun, *args, copy=False, **kwargs))
 542        return new_node
 543
 544    def replace(self, expression):
 545        """
 546        Swap out this expression with a new expression.
 547
 548        For example::
 549
 550            >>> tree = Select().select("x").from_("tbl")
 551            >>> tree.find(Column).replace(Column(this="y"))
 552            (COLUMN this: y)
 553            >>> tree.sql()
 554            'SELECT y FROM tbl'
 555
 556        Args:
 557            expression (Expression|None): new node
 558
 559        Returns:
 560            The new expression or expressions.
 561        """
 562        if not self.parent:
 563            return expression
 564
 565        parent = self.parent
 566        self.parent = None
 567
 568        replace_children(parent, lambda child: expression if child is self else child)
 569        return expression
 570
 571    def pop(self):
 572        """
 573        Remove this expression from its AST.
 574
 575        Returns:
 576            The popped expression.
 577        """
 578        self.replace(None)
 579        return self
 580
 581    def assert_is(self, type_):
 582        """
 583        Assert that this `Expression` is an instance of `type_`.
 584
 585        If it is NOT an instance of `type_`, this raises an assertion error.
 586        Otherwise, this returns this expression.
 587
 588        Examples:
 589            This is useful for type security in chained expressions:
 590
 591            >>> import sqlglot
 592            >>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql()
 593            'SELECT x, z FROM y'
 594        """
 595        assert isinstance(self, type_)
 596        return self
 597
 598    def error_messages(self, args: t.Optional[t.Sequence] = None) -> t.List[str]:
 599        """
 600        Checks if this expression is valid (e.g. all mandatory args are set).
 601
 602        Args:
 603            args: a sequence of values that were used to instantiate a Func expression. This is used
 604                to check that the provided arguments don't exceed the function argument limit.
 605
 606        Returns:
 607            A list of error messages for all possible errors that were found.
 608        """
 609        errors: t.List[str] = []
 610
 611        for k in self.args:
 612            if k not in self.arg_types:
 613                errors.append(f"Unexpected keyword: '{k}' for {self.__class__}")
 614        for k, mandatory in self.arg_types.items():
 615            v = self.args.get(k)
 616            if mandatory and (v is None or (isinstance(v, list) and not v)):
 617                errors.append(f"Required keyword: '{k}' missing for {self.__class__}")
 618
 619        if (
 620            args
 621            and isinstance(self, Func)
 622            and len(args) > len(self.arg_types)
 623            and not self.is_var_len_args
 624        ):
 625            errors.append(
 626                f"The number of provided arguments ({len(args)}) is greater than "
 627                f"the maximum number of supported arguments ({len(self.arg_types)})"
 628            )
 629
 630        return errors
 631
 632    def dump(self):
 633        """
 634        Dump this Expression to a JSON-serializable dict.
 635        """
 636        from sqlglot.serde import dump
 637
 638        return dump(self)
 639
 640    @classmethod
 641    def load(cls, obj):
 642        """
 643        Load a dict (as returned by `Expression.dump`) into an Expression instance.
 644        """
 645        from sqlglot.serde import load
 646
 647        return load(obj)
 648
 649
 650IntoType = t.Union[
 651    str,
 652    t.Type[Expression],
 653    t.Collection[t.Union[str, t.Type[Expression]]],
 654]
 655ExpOrStr = t.Union[str, Expression]
 656
 657
 658class Condition(Expression):
 659    def and_(self, *expressions, dialect=None, copy=True, **opts):
 660        """
 661        AND this condition with one or multiple expressions.
 662
 663        Example:
 664            >>> condition("x=1").and_("y=1").sql()
 665            'x = 1 AND y = 1'
 666
 667        Args:
 668            *expressions (str | Expression): the SQL code strings to parse.
 669                If an `Expression` instance is passed, it will be used as-is.
 670            dialect (str): the dialect used to parse the input expression.
 671            copy (bool): whether or not to copy the involved expressions (only applies to Expressions).
 672            opts (kwargs): other options to use to parse the input expressions.
 673
 674        Returns:
 675            And: the new condition.
 676        """
 677        return and_(self, *expressions, dialect=dialect, copy=copy, **opts)
 678
 679    def or_(self, *expressions, dialect=None, copy=True, **opts):
 680        """
 681        OR this condition with one or multiple expressions.
 682
 683        Example:
 684            >>> condition("x=1").or_("y=1").sql()
 685            'x = 1 OR y = 1'
 686
 687        Args:
 688            *expressions (str | Expression): the SQL code strings to parse.
 689                If an `Expression` instance is passed, it will be used as-is.
 690            dialect (str): the dialect used to parse the input expression.
 691            copy (bool): whether or not to copy the involved expressions (only applies to Expressions).
 692            opts (kwargs): other options to use to parse the input expressions.
 693
 694        Returns:
 695            Or: the new condition.
 696        """
 697        return or_(self, *expressions, dialect=dialect, copy=copy, **opts)
 698
 699    def not_(self, copy=True):
 700        """
 701        Wrap this condition with NOT.
 702
 703        Example:
 704            >>> condition("x=1").not_().sql()
 705            'NOT x = 1'
 706
 707        Args:
 708            copy (bool): whether or not to copy this object.
 709
 710        Returns:
 711            Not: the new condition.
 712        """
 713        return not_(self, copy=copy)
 714
 715    def _binop(self, klass: t.Type[E], other: t.Any, reverse: bool = False) -> E:
 716        this = self.copy()
 717        other = convert(other, copy=True)
 718        if not isinstance(this, klass) and not isinstance(other, klass):
 719            this = _wrap(this, Binary)
 720            other = _wrap(other, Binary)
 721        if reverse:
 722            return klass(this=other, expression=this)
 723        return klass(this=this, expression=other)
 724
 725    def __getitem__(self, other: ExpOrStr | t.Tuple[ExpOrStr]):
 726        return Bracket(
 727            this=self.copy(), expressions=[convert(e, copy=True) for e in ensure_list(other)]
 728        )
 729
 730    def isin(
 731        self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy=True, **opts
 732    ) -> In:
 733        return In(
 734            this=_maybe_copy(self, copy),
 735            expressions=[convert(e, copy=copy) for e in expressions],
 736            query=maybe_parse(query, copy=copy, **opts) if query else None,
 737        )
 738
 739    def between(self, low: t.Any, high: t.Any, copy=True, **opts) -> Between:
 740        return Between(
 741            this=_maybe_copy(self, copy),
 742            low=convert(low, copy=copy, **opts),
 743            high=convert(high, copy=copy, **opts),
 744        )
 745
 746    def like(self, other: ExpOrStr) -> Like:
 747        return self._binop(Like, other)
 748
 749    def ilike(self, other: ExpOrStr) -> ILike:
 750        return self._binop(ILike, other)
 751
 752    def eq(self, other: t.Any) -> EQ:
 753        return self._binop(EQ, other)
 754
 755    def neq(self, other: t.Any) -> NEQ:
 756        return self._binop(NEQ, other)
 757
 758    def rlike(self, other: ExpOrStr) -> RegexpLike:
 759        return self._binop(RegexpLike, other)
 760
 761    def __lt__(self, other: t.Any) -> LT:
 762        return self._binop(LT, other)
 763
 764    def __le__(self, other: t.Any) -> LTE:
 765        return self._binop(LTE, other)
 766
 767    def __gt__(self, other: t.Any) -> GT:
 768        return self._binop(GT, other)
 769
 770    def __ge__(self, other: t.Any) -> GTE:
 771        return self._binop(GTE, other)
 772
 773    def __add__(self, other: t.Any) -> Add:
 774        return self._binop(Add, other)
 775
 776    def __radd__(self, other: t.Any) -> Add:
 777        return self._binop(Add, other, reverse=True)
 778
 779    def __sub__(self, other: t.Any) -> Sub:
 780        return self._binop(Sub, other)
 781
 782    def __rsub__(self, other: t.Any) -> Sub:
 783        return self._binop(Sub, other, reverse=True)
 784
 785    def __mul__(self, other: t.Any) -> Mul:
 786        return self._binop(Mul, other)
 787
 788    def __rmul__(self, other: t.Any) -> Mul:
 789        return self._binop(Mul, other, reverse=True)
 790
 791    def __truediv__(self, other: t.Any) -> Div:
 792        return self._binop(Div, other)
 793
 794    def __rtruediv__(self, other: t.Any) -> Div:
 795        return self._binop(Div, other, reverse=True)
 796
 797    def __floordiv__(self, other: t.Any) -> IntDiv:
 798        return self._binop(IntDiv, other)
 799
 800    def __rfloordiv__(self, other: t.Any) -> IntDiv:
 801        return self._binop(IntDiv, other, reverse=True)
 802
 803    def __mod__(self, other: t.Any) -> Mod:
 804        return self._binop(Mod, other)
 805
 806    def __rmod__(self, other: t.Any) -> Mod:
 807        return self._binop(Mod, other, reverse=True)
 808
 809    def __pow__(self, other: t.Any) -> Pow:
 810        return self._binop(Pow, other)
 811
 812    def __rpow__(self, other: t.Any) -> Pow:
 813        return self._binop(Pow, other, reverse=True)
 814
 815    def __and__(self, other: t.Any) -> And:
 816        return self._binop(And, other)
 817
 818    def __rand__(self, other: t.Any) -> And:
 819        return self._binop(And, other, reverse=True)
 820
 821    def __or__(self, other: t.Any) -> Or:
 822        return self._binop(Or, other)
 823
 824    def __ror__(self, other: t.Any) -> Or:
 825        return self._binop(Or, other, reverse=True)
 826
 827    def __neg__(self) -> Neg:
 828        return Neg(this=_wrap(self.copy(), Binary))
 829
 830    def __invert__(self) -> Not:
 831        return not_(self.copy())
 832
 833
 834class Predicate(Condition):
 835    """Relationships like x = y, x > 1, x >= y."""
 836
 837
 838class DerivedTable(Expression):
 839    @property
 840    def alias_column_names(self):
 841        table_alias = self.args.get("alias")
 842        if not table_alias:
 843            return []
 844        column_list = table_alias.assert_is(TableAlias).args.get("columns") or []
 845        return [c.name for c in column_list]
 846
 847    @property
 848    def selects(self):
 849        return self.this.selects if isinstance(self.this, Subqueryable) else []
 850
 851    @property
 852    def named_selects(self):
 853        return [select.output_name for select in self.selects]
 854
 855
 856class Unionable(Expression):
 857    def union(self, expression, distinct=True, dialect=None, **opts):
 858        """
 859        Builds a UNION expression.
 860
 861        Example:
 862            >>> import sqlglot
 863            >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
 864            'SELECT * FROM foo UNION SELECT * FROM bla'
 865
 866        Args:
 867            expression (str | Expression): the SQL code string.
 868                If an `Expression` instance is passed, it will be used as-is.
 869            distinct (bool): set the DISTINCT flag if and only if this is true.
 870            dialect (str): the dialect used to parse the input expression.
 871            opts (kwargs): other options to use to parse the input expressions.
 872        Returns:
 873            Union: the Union expression.
 874        """
 875        return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
 876
 877    def intersect(self, expression, distinct=True, dialect=None, **opts):
 878        """
 879        Builds an INTERSECT expression.
 880
 881        Example:
 882            >>> import sqlglot
 883            >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
 884            'SELECT * FROM foo INTERSECT SELECT * FROM bla'
 885
 886        Args:
 887            expression (str | Expression): the SQL code string.
 888                If an `Expression` instance is passed, it will be used as-is.
 889            distinct (bool): set the DISTINCT flag if and only if this is true.
 890            dialect (str): the dialect used to parse the input expression.
 891            opts (kwargs): other options to use to parse the input expressions.
 892        Returns:
 893            Intersect: the Intersect expression
 894        """
 895        return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
 896
 897    def except_(self, expression, distinct=True, dialect=None, **opts):
 898        """
 899        Builds an EXCEPT expression.
 900
 901        Example:
 902            >>> import sqlglot
 903            >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
 904            'SELECT * FROM foo EXCEPT SELECT * FROM bla'
 905
 906        Args:
 907            expression (str | Expression): the SQL code string.
 908                If an `Expression` instance is passed, it will be used as-is.
 909            distinct (bool): set the DISTINCT flag if and only if this is true.
 910            dialect (str): the dialect used to parse the input expression.
 911            opts (kwargs): other options to use to parse the input expressions.
 912        Returns:
 913            Except: the Except expression
 914        """
 915        return except_(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
 916
 917
 918class UDTF(DerivedTable, Unionable):
 919    @property
 920    def selects(self):
 921        alias = self.args.get("alias")
 922        return alias.columns if alias else []
 923
 924
 925class Cache(Expression):
 926    arg_types = {
 927        "with": False,
 928        "this": True,
 929        "lazy": False,
 930        "options": False,
 931        "expression": False,
 932    }
 933
 934
 935class Uncache(Expression):
 936    arg_types = {"this": True, "exists": False}
 937
 938
 939class Create(Expression):
 940    arg_types = {
 941        "with": False,
 942        "this": True,
 943        "kind": True,
 944        "expression": False,
 945        "exists": False,
 946        "properties": False,
 947        "replace": False,
 948        "unique": False,
 949        "indexes": False,
 950        "no_schema_binding": False,
 951        "begin": False,
 952    }
 953
 954
 955class Describe(Expression):
 956    arg_types = {"this": True, "kind": False}
 957
 958
 959class Pragma(Expression):
 960    pass
 961
 962
 963class Set(Expression):
 964    arg_types = {"expressions": False}
 965
 966
 967class SetItem(Expression):
 968    arg_types = {
 969        "this": False,
 970        "expressions": False,
 971        "kind": False,
 972        "collate": False,  # MySQL SET NAMES statement
 973        "global": False,
 974    }
 975
 976
 977class Show(Expression):
 978    arg_types = {
 979        "this": True,
 980        "target": False,
 981        "offset": False,
 982        "limit": False,
 983        "like": False,
 984        "where": False,
 985        "db": False,
 986        "full": False,
 987        "mutex": False,
 988        "query": False,
 989        "channel": False,
 990        "global": False,
 991        "log": False,
 992        "position": False,
 993        "types": False,
 994    }
 995
 996
 997class UserDefinedFunction(Expression):
 998    arg_types = {"this": True, "expressions": False, "wrapped": False}
 999
1000
1001class CharacterSet(Expression):
1002    arg_types = {"this": True, "default": False}
1003
1004
1005class With(Expression):
1006    arg_types = {"expressions": True, "recursive": False}
1007
1008    @property
1009    def recursive(self) -> bool:
1010        return bool(self.args.get("recursive"))
1011
1012
1013class WithinGroup(Expression):
1014    arg_types = {"this": True, "expression": False}
1015
1016
1017class CTE(DerivedTable):
1018    arg_types = {"this": True, "alias": True}
1019
1020
1021class TableAlias(Expression):
1022    arg_types = {"this": False, "columns": False}
1023
1024    @property
1025    def columns(self):
1026        return self.args.get("columns") or []
1027
1028
1029class BitString(Condition):
1030    pass
1031
1032
1033class HexString(Condition):
1034    pass
1035
1036
1037class ByteString(Condition):
1038    pass
1039
1040
1041class Column(Condition):
1042    arg_types = {"this": True, "table": False, "db": False, "catalog": False, "join_mark": False}
1043
1044    @property
1045    def table(self) -> str:
1046        return self.text("table")
1047
1048    @property
1049    def db(self) -> str:
1050        return self.text("db")
1051
1052    @property
1053    def catalog(self) -> str:
1054        return self.text("catalog")
1055
1056    @property
1057    def output_name(self) -> str:
1058        return self.name
1059
1060    @property
1061    def parts(self) -> t.List[Identifier]:
1062        """Return the parts of a column in order catalog, db, table, name."""
1063        return [
1064            t.cast(Identifier, self.args[part])
1065            for part in ("catalog", "db", "table", "this")
1066            if self.args.get(part)
1067        ]
1068
1069    def to_dot(self) -> Dot:
1070        """Converts the column into a dot expression."""
1071        parts = self.parts
1072        parent = self.parent
1073
1074        while parent:
1075            if isinstance(parent, Dot):
1076                parts.append(parent.expression)
1077            parent = parent.parent
1078
1079        return Dot.build(parts)
1080
1081
1082class ColumnPosition(Expression):
1083    arg_types = {"this": False, "position": True}
1084
1085
1086class ColumnDef(Expression):
1087    arg_types = {
1088        "this": True,
1089        "kind": False,
1090        "constraints": False,
1091        "exists": False,
1092        "position": False,
1093    }
1094
1095    @property
1096    def constraints(self) -> t.List[ColumnConstraint]:
1097        return self.args.get("constraints") or []
1098
1099
1100class AlterColumn(Expression):
1101    arg_types = {
1102        "this": True,
1103        "dtype": False,
1104        "collate": False,
1105        "using": False,
1106        "default": False,
1107        "drop": False,
1108    }
1109
1110
1111class RenameTable(Expression):
1112    pass
1113
1114
1115class SetTag(Expression):
1116    arg_types = {"expressions": True, "unset": False}
1117
1118
1119class Comment(Expression):
1120    arg_types = {"this": True, "kind": True, "expression": True, "exists": False}
1121
1122
1123# https://clickhouse.com/docs/en/engines/table-engines/mergetree-family/mergetree#mergetree-table-ttl
1124class MergeTreeTTLAction(Expression):
1125    arg_types = {
1126        "this": True,
1127        "delete": False,
1128        "recompress": False,
1129        "to_disk": False,
1130        "to_volume": False,
1131    }
1132
1133
1134# https://clickhouse.com/docs/en/engines/table-engines/mergetree-family/mergetree#mergetree-table-ttl
1135class MergeTreeTTL(Expression):
1136    arg_types = {
1137        "expressions": True,
1138        "where": False,
1139        "group": False,
1140        "aggregates": False,
1141    }
1142
1143
1144class ColumnConstraint(Expression):
1145    arg_types = {"this": False, "kind": True}
1146
1147    @property
1148    def kind(self) -> ColumnConstraintKind:
1149        return self.args["kind"]
1150
1151
1152class ColumnConstraintKind(Expression):
1153    pass
1154
1155
1156class AutoIncrementColumnConstraint(ColumnConstraintKind):
1157    pass
1158
1159
1160class CaseSpecificColumnConstraint(ColumnConstraintKind):
1161    arg_types = {"not_": True}
1162
1163
1164class CharacterSetColumnConstraint(ColumnConstraintKind):
1165    arg_types = {"this": True}
1166
1167
1168class CheckColumnConstraint(ColumnConstraintKind):
1169    pass
1170
1171
1172class CollateColumnConstraint(ColumnConstraintKind):
1173    pass
1174
1175
1176class CommentColumnConstraint(ColumnConstraintKind):
1177    pass
1178
1179
1180class CompressColumnConstraint(ColumnConstraintKind):
1181    pass
1182
1183
1184class DateFormatColumnConstraint(ColumnConstraintKind):
1185    arg_types = {"this": True}
1186
1187
1188class DefaultColumnConstraint(ColumnConstraintKind):
1189    pass
1190
1191
1192class EncodeColumnConstraint(ColumnConstraintKind):
1193    pass
1194
1195
1196class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind):
1197    # this: True -> ALWAYS, this: False -> BY DEFAULT
1198    arg_types = {
1199        "this": False,
1200        "on_null": False,
1201        "start": False,
1202        "increment": False,
1203        "minvalue": False,
1204        "maxvalue": False,
1205        "cycle": False,
1206    }
1207
1208
1209class InlineLengthColumnConstraint(ColumnConstraintKind):
1210    pass
1211
1212
1213class NotNullColumnConstraint(ColumnConstraintKind):
1214    arg_types = {"allow_null": False}
1215
1216
1217# https://dev.mysql.com/doc/refman/5.7/en/timestamp-initialization.html
1218class OnUpdateColumnConstraint(ColumnConstraintKind):
1219    pass
1220
1221
1222class PrimaryKeyColumnConstraint(ColumnConstraintKind):
1223    arg_types = {"desc": False}
1224
1225
1226class TitleColumnConstraint(ColumnConstraintKind):
1227    pass
1228
1229
1230class UniqueColumnConstraint(ColumnConstraintKind):
1231    arg_types: t.Dict[str, t.Any] = {}
1232
1233
1234class UppercaseColumnConstraint(ColumnConstraintKind):
1235    arg_types: t.Dict[str, t.Any] = {}
1236
1237
1238class PathColumnConstraint(ColumnConstraintKind):
1239    pass
1240
1241
1242class Constraint(Expression):
1243    arg_types = {"this": True, "expressions": True}
1244
1245
1246class Delete(Expression):
1247    arg_types = {"with": False, "this": False, "using": False, "where": False, "returning": False}
1248
1249    def delete(
1250        self,
1251        table: ExpOrStr,
1252        dialect: DialectType = None,
1253        copy: bool = True,
1254        **opts,
1255    ) -> Delete:
1256        """
1257        Create a DELETE expression or replace the table on an existing DELETE expression.
1258
1259        Example:
1260            >>> delete("tbl").sql()
1261            'DELETE FROM tbl'
1262
1263        Args:
1264            table: the table from which to delete.
1265            dialect: the dialect used to parse the input expression.
1266            copy: if `False`, modify this expression instance in-place.
1267            opts: other options to use to parse the input expressions.
1268
1269        Returns:
1270            Delete: the modified expression.
1271        """
1272        return _apply_builder(
1273            expression=table,
1274            instance=self,
1275            arg="this",
1276            dialect=dialect,
1277            into=Table,
1278            copy=copy,
1279            **opts,
1280        )
1281
1282    def where(
1283        self,
1284        *expressions: ExpOrStr,
1285        append: bool = True,
1286        dialect: DialectType = None,
1287        copy: bool = True,
1288        **opts,
1289    ) -> Delete:
1290        """
1291        Append to or set the WHERE expressions.
1292
1293        Example:
1294            >>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
1295            "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
1296
1297        Args:
1298            *expressions: the SQL code strings to parse.
1299                If an `Expression` instance is passed, it will be used as-is.
1300                Multiple expressions are combined with an AND operator.
1301            append: if `True`, AND the new expressions to any existing expression.
1302                Otherwise, this resets the expression.
1303            dialect: the dialect used to parse the input expressions.
1304            copy: if `False`, modify this expression instance in-place.
1305            opts: other options to use to parse the input expressions.
1306
1307        Returns:
1308            Delete: the modified expression.
1309        """
1310        return _apply_conjunction_builder(
1311            *expressions,
1312            instance=self,
1313            arg="where",
1314            append=append,
1315            into=Where,
1316            dialect=dialect,
1317            copy=copy,
1318            **opts,
1319        )
1320
1321    def returning(
1322        self,
1323        expression: ExpOrStr,
1324        dialect: DialectType = None,
1325        copy: bool = True,
1326        **opts,
1327    ) -> Delete:
1328        """
1329        Set the RETURNING expression. Not supported by all dialects.
1330
1331        Example:
1332            >>> delete("tbl").returning("*", dialect="postgres").sql()
1333            'DELETE FROM tbl RETURNING *'
1334
1335        Args:
1336            expression: the SQL code strings to parse.
1337                If an `Expression` instance is passed, it will be used as-is.
1338            dialect: the dialect used to parse the input expressions.
1339            copy: if `False`, modify this expression instance in-place.
1340            opts: other options to use to parse the input expressions.
1341
1342        Returns:
1343            Delete: the modified expression.
1344        """
1345        return _apply_builder(
1346            expression=expression,
1347            instance=self,
1348            arg="returning",
1349            prefix="RETURNING",
1350            dialect=dialect,
1351            copy=copy,
1352            into=Returning,
1353            **opts,
1354        )
1355
1356
1357class Drop(Expression):
1358    arg_types = {
1359        "this": False,
1360        "kind": False,
1361        "exists": False,
1362        "temporary": False,
1363        "materialized": False,
1364        "cascade": False,
1365        "constraints": False,
1366        "purge": False,
1367    }
1368
1369
1370class Filter(Expression):
1371    arg_types = {"this": True, "expression": True}
1372
1373
1374class Check(Expression):
1375    pass
1376
1377
1378class Directory(Expression):
1379    # https://spark.apache.org/docs/3.0.0-preview/sql-ref-syntax-dml-insert-overwrite-directory-hive.html
1380    arg_types = {"this": True, "local": False, "row_format": False}
1381
1382
1383class ForeignKey(Expression):
1384    arg_types = {
1385        "expressions": True,
1386        "reference": False,
1387        "delete": False,
1388        "update": False,
1389    }
1390
1391
1392class PrimaryKey(Expression):
1393    arg_types = {"expressions": True, "options": False}
1394
1395
1396class Unique(Expression):
1397    arg_types = {"expressions": True}
1398
1399
1400# https://www.postgresql.org/docs/9.1/sql-selectinto.html
1401# https://docs.aws.amazon.com/redshift/latest/dg/r_SELECT_INTO.html#r_SELECT_INTO-examples
1402class Into(Expression):
1403    arg_types = {"this": True, "temporary": False, "unlogged": False}
1404
1405
1406class From(Expression):
1407    arg_types = {"expressions": True}
1408
1409
1410class Having(Expression):
1411    pass
1412
1413
1414class Hint(Expression):
1415    arg_types = {"expressions": True}
1416
1417
1418class JoinHint(Expression):
1419    arg_types = {"this": True, "expressions": True}
1420
1421
1422class Identifier(Expression):
1423    arg_types = {"this": True, "quoted": False}
1424
1425    @property
1426    def quoted(self):
1427        return bool(self.args.get("quoted"))
1428
1429    @property
1430    def hashable_args(self) -> t.Any:
1431        if self.quoted and any(char.isupper() for char in self.this):
1432            return (self.this, self.quoted)
1433        return self.this.lower()
1434
1435    @property
1436    def output_name(self):
1437        return self.name
1438
1439
1440class Index(Expression):
1441    arg_types = {
1442        "this": False,
1443        "table": False,
1444        "where": False,
1445        "columns": False,
1446        "unique": False,
1447        "primary": False,
1448        "amp": False,  # teradata
1449    }
1450
1451
1452class Insert(Expression):
1453    arg_types = {
1454        "with": False,
1455        "this": True,
1456        "expression": False,
1457        "conflict": False,
1458        "returning": False,
1459        "overwrite": False,
1460        "exists": False,
1461        "partition": False,
1462        "alternative": False,
1463    }
1464
1465
1466class OnConflict(Expression):
1467    arg_types = {
1468        "duplicate": False,
1469        "expressions": False,
1470        "nothing": False,
1471        "key": False,
1472        "constraint": False,
1473    }
1474
1475
1476class Returning(Expression):
1477    arg_types = {"expressions": True}
1478
1479
1480# https://dev.mysql.com/doc/refman/8.0/en/charset-introducer.html
1481class Introducer(Expression):
1482    arg_types = {"this": True, "expression": True}
1483
1484
1485# national char, like n'utf8'
1486class National(Expression):
1487    pass
1488
1489
1490class LoadData(Expression):
1491    arg_types = {
1492        "this": True,
1493        "local": False,
1494        "overwrite": False,
1495        "inpath": True,
1496        "partition": False,
1497        "input_format": False,
1498        "serde": False,
1499    }
1500
1501
1502class Partition(Expression):
1503    arg_types = {"expressions": True}
1504
1505
1506class Fetch(Expression):
1507    arg_types = {
1508        "direction": False,
1509        "count": False,
1510        "percent": False,
1511        "with_ties": False,
1512    }
1513
1514
1515class Group(Expression):
1516    arg_types = {
1517        "expressions": False,
1518        "grouping_sets": False,
1519        "cube": False,
1520        "rollup": False,
1521    }
1522
1523
1524class Lambda(Expression):
1525    arg_types = {"this": True, "expressions": True}
1526
1527
1528class Limit(Expression):
1529    arg_types = {"this": False, "expression": True}
1530
1531
1532class Literal(Condition):
1533    arg_types = {"this": True, "is_string": True}
1534
1535    @property
1536    def hashable_args(self) -> t.Any:
1537        return (self.this, self.args.get("is_string"))
1538
1539    @classmethod
1540    def number(cls, number) -> Literal:
1541        return cls(this=str(number), is_string=False)
1542
1543    @classmethod
1544    def string(cls, string) -> Literal:
1545        return cls(this=str(string), is_string=True)
1546
1547    @property
1548    def output_name(self):
1549        return self.name
1550
1551
1552class Join(Expression):
1553    arg_types = {
1554        "this": True,
1555        "on": False,
1556        "side": False,
1557        "kind": False,
1558        "using": False,
1559        "natural": False,
1560        "hint": False,
1561    }
1562
1563    @property
1564    def kind(self):
1565        return self.text("kind").upper()
1566
1567    @property
1568    def side(self):
1569        return self.text("side").upper()
1570
1571    @property
1572    def hint(self):
1573        return self.text("hint").upper()
1574
1575    @property
1576    def alias_or_name(self):
1577        return self.this.alias_or_name
1578
1579    def on(self, *expressions, append=True, dialect=None, copy=True, **opts):
1580        """
1581        Append to or set the ON expressions.
1582
1583        Example:
1584            >>> import sqlglot
1585            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1586            'JOIN x ON y = 1'
1587
1588        Args:
1589            *expressions (str | Expression): the SQL code strings to parse.
1590                If an `Expression` instance is passed, it will be used as-is.
1591                Multiple expressions are combined with an AND operator.
1592            append (bool): if `True`, AND the new expressions to any existing expression.
1593                Otherwise, this resets the expression.
1594            dialect (str): the dialect used to parse the input expressions.
1595            copy (bool): if `False`, modify this expression instance in-place.
1596            opts (kwargs): other options to use to parse the input expressions.
1597
1598        Returns:
1599            Join: the modified join expression.
1600        """
1601        join = _apply_conjunction_builder(
1602            *expressions,
1603            instance=self,
1604            arg="on",
1605            append=append,
1606            dialect=dialect,
1607            copy=copy,
1608            **opts,
1609        )
1610
1611        if join.kind == "CROSS":
1612            join.set("kind", None)
1613
1614        return join
1615
1616    def using(self, *expressions, append=True, dialect=None, copy=True, **opts):
1617        """
1618        Append to or set the USING expressions.
1619
1620        Example:
1621            >>> import sqlglot
1622            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1623            'JOIN x USING (foo, bla)'
1624
1625        Args:
1626            *expressions (str | Expression): the SQL code strings to parse.
1627                If an `Expression` instance is passed, it will be used as-is.
1628            append (bool): if `True`, concatenate the new expressions to the existing "using" list.
1629                Otherwise, this resets the expression.
1630            dialect (str): the dialect used to parse the input expressions.
1631            copy (bool): if `False`, modify this expression instance in-place.
1632            opts (kwargs): other options to use to parse the input expressions.
1633
1634        Returns:
1635            Join: the modified join expression.
1636        """
1637        join = _apply_list_builder(
1638            *expressions,
1639            instance=self,
1640            arg="using",
1641            append=append,
1642            dialect=dialect,
1643            copy=copy,
1644            **opts,
1645        )
1646
1647        if join.kind == "CROSS":
1648            join.set("kind", None)
1649
1650        return join
1651
1652
1653class Lateral(UDTF):
1654    arg_types = {"this": True, "view": False, "outer": False, "alias": False}
1655
1656
1657class MatchRecognize(Expression):
1658    arg_types = {
1659        "partition_by": False,
1660        "order": False,
1661        "measures": False,
1662        "rows": False,
1663        "after": False,
1664        "pattern": False,
1665        "define": False,
1666        "alias": False,
1667    }
1668
1669
1670# Clickhouse FROM FINAL modifier
1671# https://clickhouse.com/docs/en/sql-reference/statements/select/from/#final-modifier
1672class Final(Expression):
1673    pass
1674
1675
1676class Offset(Expression):
1677    arg_types = {"this": False, "expression": True}
1678
1679
1680class Order(Expression):
1681    arg_types = {"this": False, "expressions": True}
1682
1683
1684# hive specific sorts
1685# https://cwiki.apache.org/confluence/display/Hive/LanguageManual+SortBy
1686class Cluster(Order):
1687    pass
1688
1689
1690class Distribute(Order):
1691    pass
1692
1693
1694class Sort(Order):
1695    pass
1696
1697
1698class Ordered(Expression):
1699    arg_types = {"this": True, "desc": True, "nulls_first": True}
1700
1701
1702class Property(Expression):
1703    arg_types = {"this": True, "value": True}
1704
1705
1706class AfterJournalProperty(Property):
1707    arg_types = {"no": True, "dual": False, "local": False}
1708
1709
1710class AlgorithmProperty(Property):
1711    arg_types = {"this": True}
1712
1713
1714class AutoIncrementProperty(Property):
1715    arg_types = {"this": True}
1716
1717
1718class BlockCompressionProperty(Property):
1719    arg_types = {"autotemp": False, "always": False, "default": True, "manual": True, "never": True}
1720
1721
1722class CharacterSetProperty(Property):
1723    arg_types = {"this": True, "default": True}
1724
1725
1726class ChecksumProperty(Property):
1727    arg_types = {"on": False, "default": False}
1728
1729
1730class CollateProperty(Property):
1731    arg_types = {"this": True}
1732
1733
1734class DataBlocksizeProperty(Property):
1735    arg_types = {"size": False, "units": False, "min": False, "default": False}
1736
1737
1738class DefinerProperty(Property):
1739    arg_types = {"this": True}
1740
1741
1742class DistKeyProperty(Property):
1743    arg_types = {"this": True}
1744
1745
1746class DistStyleProperty(Property):
1747    arg_types = {"this": True}
1748
1749
1750class EngineProperty(Property):
1751    arg_types = {"this": True}
1752
1753
1754class ExecuteAsProperty(Property):
1755    arg_types = {"this": True}
1756
1757
1758class ExternalProperty(Property):
1759    arg_types = {"this": False}
1760
1761
1762class FallbackProperty(Property):
1763    arg_types = {"no": True, "protection": False}
1764
1765
1766class FileFormatProperty(Property):
1767    arg_types = {"this": True}
1768
1769
1770class FreespaceProperty(Property):
1771    arg_types = {"this": True, "percent": False}
1772
1773
1774class InputOutputFormat(Expression):
1775    arg_types = {"input_format": False, "output_format": False}
1776
1777
1778class IsolatedLoadingProperty(Property):
1779    arg_types = {
1780        "no": True,
1781        "concurrent": True,
1782        "for_all": True,
1783        "for_insert": True,
1784        "for_none": True,
1785    }
1786
1787
1788class JournalProperty(Property):
1789    arg_types = {"no": True, "dual": False, "before": False}
1790
1791
1792class LanguageProperty(Property):
1793    arg_types = {"this": True}
1794
1795
1796class LikeProperty(Property):
1797    arg_types = {"this": True, "expressions": False}
1798
1799
1800class LocationProperty(Property):
1801    arg_types = {"this": True}
1802
1803
1804class LockingProperty(Property):
1805    arg_types = {
1806        "this": False,
1807        "kind": True,
1808        "for_or_in": True,
1809        "lock_type": True,
1810        "override": False,
1811    }
1812
1813
1814class LogProperty(Property):
1815    arg_types = {"no": True}
1816
1817
1818class MaterializedProperty(Property):
1819    arg_types = {"this": False}
1820
1821
1822class MergeBlockRatioProperty(Property):
1823    arg_types = {"this": False, "no": False, "default": False, "percent": False}
1824
1825
1826class NoPrimaryIndexProperty(Property):
1827    arg_types = {"this": False}
1828
1829
1830class OnCommitProperty(Property):
1831    arg_type = {"this": False}
1832
1833
1834class PartitionedByProperty(Property):
1835    arg_types = {"this": True}
1836
1837
1838class ReturnsProperty(Property):
1839    arg_types = {"this": True, "is_table": False, "table": False}
1840
1841
1842class RowFormatProperty(Property):
1843    arg_types = {"this": True}
1844
1845
1846class RowFormatDelimitedProperty(Property):
1847    # https://cwiki.apache.org/confluence/display/hive/languagemanual+dml
1848    arg_types = {
1849        "fields": False,
1850        "escaped": False,
1851        "collection_items": False,
1852        "map_keys": False,
1853        "lines": False,
1854        "null": False,
1855        "serde": False,
1856    }
1857
1858
1859class RowFormatSerdeProperty(Property):
1860    arg_types = {"this": True}
1861
1862
1863class SchemaCommentProperty(Property):
1864    arg_types = {"this": True}
1865
1866
1867class SerdeProperties(Property):
1868    arg_types = {"expressions": True}
1869
1870
1871class SetProperty(Property):
1872    arg_types = {"multi": True}
1873
1874
1875class SettingsProperty(Property):
1876    arg_types = {"expressions": True}
1877
1878
1879class SortKeyProperty(Property):
1880    arg_types = {"this": True, "compound": False}
1881
1882
1883class SqlSecurityProperty(Property):
1884    arg_types = {"definer": True}
1885
1886
1887class StabilityProperty(Property):
1888    arg_types = {"this": True}
1889
1890
1891class TableFormatProperty(Property):
1892    arg_types = {"this": True}
1893
1894
1895class TemporaryProperty(Property):
1896    arg_types = {"global_": True}
1897
1898
1899class TransientProperty(Property):
1900    arg_types = {"this": False}
1901
1902
1903class VolatileProperty(Property):
1904    arg_types = {"this": False}
1905
1906
1907class WithDataProperty(Property):
1908    arg_types = {"no": True, "statistics": False}
1909
1910
1911class WithJournalTableProperty(Property):
1912    arg_types = {"this": True}
1913
1914
1915class Properties(Expression):
1916    arg_types = {"expressions": True}
1917
1918    NAME_TO_PROPERTY = {
1919        "ALGORITHM": AlgorithmProperty,
1920        "AUTO_INCREMENT": AutoIncrementProperty,
1921        "CHARACTER SET": CharacterSetProperty,
1922        "COLLATE": CollateProperty,
1923        "COMMENT": SchemaCommentProperty,
1924        "DEFINER": DefinerProperty,
1925        "DISTKEY": DistKeyProperty,
1926        "DISTSTYLE": DistStyleProperty,
1927        "ENGINE": EngineProperty,
1928        "EXECUTE AS": ExecuteAsProperty,
1929        "FORMAT": FileFormatProperty,
1930        "LANGUAGE": LanguageProperty,
1931        "LOCATION": LocationProperty,
1932        "PARTITIONED_BY": PartitionedByProperty,
1933        "RETURNS": ReturnsProperty,
1934        "ROW_FORMAT": RowFormatProperty,
1935        "SORTKEY": SortKeyProperty,
1936        "TABLE_FORMAT": TableFormatProperty,
1937    }
1938
1939    PROPERTY_TO_NAME = {v: k for k, v in NAME_TO_PROPERTY.items()}
1940
1941    # CREATE property locations
1942    # Form: schema specified
1943    #   create [POST_CREATE]
1944    #     table a [POST_NAME]
1945    #     (b int) [POST_SCHEMA]
1946    #     with ([POST_WITH])
1947    #     index (b) [POST_INDEX]
1948    #
1949    # Form: alias selection
1950    #   create [POST_CREATE]
1951    #     table a [POST_NAME]
1952    #     as [POST_ALIAS] (select * from b) [POST_EXPRESSION]
1953    #     index (c) [POST_INDEX]
1954    class Location(AutoName):
1955        POST_CREATE = auto()
1956        POST_NAME = auto()
1957        POST_SCHEMA = auto()
1958        POST_WITH = auto()
1959        POST_ALIAS = auto()
1960        POST_EXPRESSION = auto()
1961        POST_INDEX = auto()
1962        UNSUPPORTED = auto()
1963
1964    @classmethod
1965    def from_dict(cls, properties_dict) -> Properties:
1966        expressions = []
1967        for key, value in properties_dict.items():
1968            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
1969            if property_cls:
1970                expressions.append(property_cls(this=convert(value)))
1971            else:
1972                expressions.append(Property(this=Literal.string(key), value=convert(value)))
1973
1974        return cls(expressions=expressions)
1975
1976
1977class Qualify(Expression):
1978    pass
1979
1980
1981# https://www.ibm.com/docs/en/ias?topic=procedures-return-statement-in-sql
1982class Return(Expression):
1983    pass
1984
1985
1986class Reference(Expression):
1987    arg_types = {"this": True, "expressions": False, "options": False}
1988
1989
1990class Tuple(Expression):
1991    arg_types = {"expressions": False}
1992
1993    def isin(
1994        self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy=True, **opts
1995    ) -> In:
1996        return In(
1997            this=_maybe_copy(self, copy),
1998            expressions=[convert(e, copy=copy) for e in expressions],
1999            query=maybe_parse(query, copy=copy, **opts) if query else None,
2000        )
2001
2002
2003class Subqueryable(Unionable):
2004    def subquery(self, alias=None, copy=True) -> Subquery:
2005        """
2006        Convert this expression to an aliased expression that can be used as a Subquery.
2007
2008        Example:
2009            >>> subquery = Select().select("x").from_("tbl").subquery()
2010            >>> Select().select("x").from_(subquery).sql()
2011            'SELECT x FROM (SELECT x FROM tbl)'
2012
2013        Args:
2014            alias (str | Identifier): an optional alias for the subquery
2015            copy (bool): if `False`, modify this expression instance in-place.
2016
2017        Returns:
2018            Alias: the subquery
2019        """
2020        instance = _maybe_copy(self, copy)
2021        return Subquery(
2022            this=instance,
2023            alias=TableAlias(this=to_identifier(alias)) if alias else None,
2024        )
2025
2026    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
2027        raise NotImplementedError
2028
2029    @property
2030    def ctes(self):
2031        with_ = self.args.get("with")
2032        if not with_:
2033            return []
2034        return with_.expressions
2035
2036    @property
2037    def selects(self):
2038        raise NotImplementedError("Subqueryable objects must implement `selects`")
2039
2040    @property
2041    def named_selects(self):
2042        raise NotImplementedError("Subqueryable objects must implement `named_selects`")
2043
2044    def with_(
2045        self,
2046        alias,
2047        as_,
2048        recursive=None,
2049        append=True,
2050        dialect=None,
2051        copy=True,
2052        **opts,
2053    ):
2054        """
2055        Append to or set the common table expressions.
2056
2057        Example:
2058            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
2059            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
2060
2061        Args:
2062            alias (str | Expression): the SQL code string to parse as the table name.
2063                If an `Expression` instance is passed, this is used as-is.
2064            as_ (str | Expression): the SQL code string to parse as the table expression.
2065                If an `Expression` instance is passed, it will be used as-is.
2066            recursive (bool): set the RECURSIVE part of the expression. Defaults to `False`.
2067            append (bool): if `True`, add to any existing expressions.
2068                Otherwise, this resets the expressions.
2069            dialect (str): the dialect used to parse the input expression.
2070            copy (bool): if `False`, modify this expression instance in-place.
2071            opts (kwargs): other options to use to parse the input expressions.
2072
2073        Returns:
2074            Select: the modified expression.
2075        """
2076        alias_expression = maybe_parse(
2077            alias,
2078            dialect=dialect,
2079            into=TableAlias,
2080            **opts,
2081        )
2082        as_expression = maybe_parse(
2083            as_,
2084            dialect=dialect,
2085            **opts,
2086        )
2087        cte = CTE(
2088            this=as_expression,
2089            alias=alias_expression,
2090        )
2091        return _apply_child_list_builder(
2092            cte,
2093            instance=self,
2094            arg="with",
2095            append=append,
2096            copy=copy,
2097            into=With,
2098            properties={"recursive": recursive or False},
2099        )
2100
2101
2102QUERY_MODIFIERS = {
2103    "match": False,
2104    "laterals": False,
2105    "joins": False,
2106    "pivots": False,
2107    "where": False,
2108    "group": False,
2109    "having": False,
2110    "qualify": False,
2111    "windows": False,
2112    "distribute": False,
2113    "sort": False,
2114    "cluster": False,
2115    "order": False,
2116    "limit": False,
2117    "offset": False,
2118    "lock": False,
2119    "sample": False,
2120}
2121
2122
2123class Table(Expression):
2124    arg_types = {
2125        "this": True,
2126        "alias": False,
2127        "db": False,
2128        "catalog": False,
2129        "laterals": False,
2130        "joins": False,
2131        "pivots": False,
2132        "hints": False,
2133        "system_time": False,
2134    }
2135
2136    @property
2137    def db(self) -> str:
2138        return self.text("db")
2139
2140    @property
2141    def catalog(self) -> str:
2142        return self.text("catalog")
2143
2144    @property
2145    def parts(self) -> t.List[Identifier]:
2146        """Return the parts of a column in order catalog, db, table."""
2147        return [
2148            t.cast(Identifier, self.args[part])
2149            for part in ("catalog", "db", "this")
2150            if self.args.get(part)
2151        ]
2152
2153
2154# See the TSQL "Querying data in a system-versioned temporal table" page
2155class SystemTime(Expression):
2156    arg_types = {
2157        "this": False,
2158        "expression": False,
2159        "kind": True,
2160    }
2161
2162
2163class Union(Subqueryable):
2164    arg_types = {
2165        "with": False,
2166        "this": True,
2167        "expression": True,
2168        "distinct": False,
2169        **QUERY_MODIFIERS,
2170    }
2171
2172    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
2173        """
2174        Set the LIMIT expression.
2175
2176        Example:
2177            >>> select("1").union(select("1")).limit(1).sql()
2178            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
2179
2180        Args:
2181            expression (str | int | Expression): the SQL code string to parse.
2182                This can also be an integer.
2183                If a `Limit` instance is passed, this is used as-is.
2184                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2185            dialect (str): the dialect used to parse the input expression.
2186            copy (bool): if `False`, modify this expression instance in-place.
2187            opts (kwargs): other options to use to parse the input expressions.
2188
2189        Returns:
2190            Select: The limited subqueryable.
2191        """
2192        return (
2193            select("*")
2194            .from_(self.subquery(alias="_l_0", copy=copy))
2195            .limit(expression, dialect=dialect, copy=False, **opts)
2196        )
2197
2198    def select(
2199        self,
2200        *expressions: ExpOrStr,
2201        append: bool = True,
2202        dialect: DialectType = None,
2203        copy: bool = True,
2204        **opts,
2205    ) -> Union:
2206        """Append to or set the SELECT of the union recursively.
2207
2208        Example:
2209            >>> from sqlglot import parse_one
2210            >>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
2211            'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
2212
2213        Args:
2214            *expressions: the SQL code strings to parse.
2215                If an `Expression` instance is passed, it will be used as-is.
2216            append: if `True`, add to any existing expressions.
2217                Otherwise, this resets the expressions.
2218            dialect: the dialect used to parse the input expressions.
2219            copy: if `False`, modify this expression instance in-place.
2220            opts: other options to use to parse the input expressions.
2221
2222        Returns:
2223            Union: the modified expression.
2224        """
2225        this = self.copy() if copy else self
2226        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
2227        this.expression.unnest().select(
2228            *expressions, append=append, dialect=dialect, copy=False, **opts
2229        )
2230        return this
2231
2232    @property
2233    def named_selects(self):
2234        return self.this.unnest().named_selects
2235
2236    @property
2237    def is_star(self) -> bool:
2238        return self.this.is_star or self.expression.is_star
2239
2240    @property
2241    def selects(self):
2242        return self.this.unnest().selects
2243
2244    @property
2245    def left(self):
2246        return self.this
2247
2248    @property
2249    def right(self):
2250        return self.expression
2251
2252
2253class Except(Union):
2254    pass
2255
2256
2257class Intersect(Union):
2258    pass
2259
2260
2261class Unnest(UDTF):
2262    arg_types = {
2263        "expressions": True,
2264        "ordinality": False,
2265        "alias": False,
2266        "offset": False,
2267    }
2268
2269
2270class Update(Expression):
2271    arg_types = {
2272        "with": False,
2273        "this": False,
2274        "expressions": True,
2275        "from": False,
2276        "where": False,
2277        "returning": False,
2278    }
2279
2280
2281class Values(UDTF):
2282    arg_types = {
2283        "expressions": True,
2284        "ordinality": False,
2285        "alias": False,
2286    }
2287
2288
2289class Var(Expression):
2290    pass
2291
2292
2293class Schema(Expression):
2294    arg_types = {"this": False, "expressions": False}
2295
2296
2297# Used to represent the FOR UPDATE and FOR SHARE locking read types.
2298# https://dev.mysql.com/doc/refman/8.0/en/innodb-locking-reads.html
2299class Lock(Expression):
2300    arg_types = {"update": True}
2301
2302
2303class Select(Subqueryable):
2304    arg_types = {
2305        "with": False,
2306        "kind": False,
2307        "expressions": False,
2308        "hint": False,
2309        "distinct": False,
2310        "struct": False,  # https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax#return_query_results_as_a_value_table
2311        "value": False,
2312        "into": False,
2313        "from": False,
2314        **QUERY_MODIFIERS,
2315    }
2316
2317    def from_(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2318        """
2319        Set the FROM expression.
2320
2321        Example:
2322            >>> Select().from_("tbl").select("x").sql()
2323            'SELECT x FROM tbl'
2324
2325        Args:
2326            *expressions (str | Expression): the SQL code strings to parse.
2327                If a `From` instance is passed, this is used as-is.
2328                If another `Expression` instance is passed, it will be wrapped in a `From`.
2329            append (bool): if `True`, add to any existing expressions.
2330                Otherwise, this flattens all the `From` expression into a single expression.
2331            dialect (str): the dialect used to parse the input expression.
2332            copy (bool): if `False`, modify this expression instance in-place.
2333            opts (kwargs): other options to use to parse the input expressions.
2334
2335        Returns:
2336            Select: the modified expression.
2337        """
2338        return _apply_child_list_builder(
2339            *expressions,
2340            instance=self,
2341            arg="from",
2342            append=append,
2343            copy=copy,
2344            prefix="FROM",
2345            into=From,
2346            dialect=dialect,
2347            **opts,
2348        )
2349
2350    def group_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2351        """
2352        Set the GROUP BY expression.
2353
2354        Example:
2355            >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
2356            'SELECT x, COUNT(1) FROM tbl GROUP BY x'
2357
2358        Args:
2359            *expressions (str | Expression): the SQL code strings to parse.
2360                If a `Group` instance is passed, this is used as-is.
2361                If another `Expression` instance is passed, it will be wrapped in a `Group`.
2362                If nothing is passed in then a group by is not applied to the expression
2363            append (bool): if `True`, add to any existing expressions.
2364                Otherwise, this flattens all the `Group` expression into a single expression.
2365            dialect (str): the dialect used to parse the input expression.
2366            copy (bool): if `False`, modify this expression instance in-place.
2367            opts (kwargs): other options to use to parse the input expressions.
2368
2369        Returns:
2370            Select: the modified expression.
2371        """
2372        if not expressions:
2373            return self if not copy else self.copy()
2374        return _apply_child_list_builder(
2375            *expressions,
2376            instance=self,
2377            arg="group",
2378            append=append,
2379            copy=copy,
2380            prefix="GROUP BY",
2381            into=Group,
2382            dialect=dialect,
2383            **opts,
2384        )
2385
2386    def order_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2387        """
2388        Set the ORDER BY expression.
2389
2390        Example:
2391            >>> Select().from_("tbl").select("x").order_by("x DESC").sql()
2392            'SELECT x FROM tbl ORDER BY x DESC'
2393
2394        Args:
2395            *expressions (str | Expression): the SQL code strings to parse.
2396                If a `Group` instance is passed, this is used as-is.
2397                If another `Expression` instance is passed, it will be wrapped in a `Order`.
2398            append (bool): if `True`, add to any existing expressions.
2399                Otherwise, this flattens all the `Order` expression into a single expression.
2400            dialect (str): the dialect used to parse the input expression.
2401            copy (bool): if `False`, modify this expression instance in-place.
2402            opts (kwargs): other options to use to parse the input expressions.
2403
2404        Returns:
2405            Select: the modified expression.
2406        """
2407        return _apply_child_list_builder(
2408            *expressions,
2409            instance=self,
2410            arg="order",
2411            append=append,
2412            copy=copy,
2413            prefix="ORDER BY",
2414            into=Order,
2415            dialect=dialect,
2416            **opts,
2417        )
2418
2419    def sort_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2420        """
2421        Set the SORT BY expression.
2422
2423        Example:
2424            >>> Select().from_("tbl").select("x").sort_by("x DESC").sql()
2425            'SELECT x FROM tbl SORT BY x DESC'
2426
2427        Args:
2428            *expressions (str | Expression): the SQL code strings to parse.
2429                If a `Group` instance is passed, this is used as-is.
2430                If another `Expression` instance is passed, it will be wrapped in a `SORT`.
2431            append (bool): if `True`, add to any existing expressions.
2432                Otherwise, this flattens all the `Order` expression into a single expression.
2433            dialect (str): the dialect used to parse the input expression.
2434            copy (bool): if `False`, modify this expression instance in-place.
2435            opts (kwargs): other options to use to parse the input expressions.
2436
2437        Returns:
2438            Select: the modified expression.
2439        """
2440        return _apply_child_list_builder(
2441            *expressions,
2442            instance=self,
2443            arg="sort",
2444            append=append,
2445            copy=copy,
2446            prefix="SORT BY",
2447            into=Sort,
2448            dialect=dialect,
2449            **opts,
2450        )
2451
2452    def cluster_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2453        """
2454        Set the CLUSTER BY expression.
2455
2456        Example:
2457            >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql()
2458            'SELECT x FROM tbl CLUSTER BY x DESC'
2459
2460        Args:
2461            *expressions (str | Expression): the SQL code strings to parse.
2462                If a `Group` instance is passed, this is used as-is.
2463                If another `Expression` instance is passed, it will be wrapped in a `Cluster`.
2464            append (bool): if `True`, add to any existing expressions.
2465                Otherwise, this flattens all the `Order` expression into a single expression.
2466            dialect (str): the dialect used to parse the input expression.
2467            copy (bool): if `False`, modify this expression instance in-place.
2468            opts (kwargs): other options to use to parse the input expressions.
2469
2470        Returns:
2471            Select: the modified expression.
2472        """
2473        return _apply_child_list_builder(
2474            *expressions,
2475            instance=self,
2476            arg="cluster",
2477            append=append,
2478            copy=copy,
2479            prefix="CLUSTER BY",
2480            into=Cluster,
2481            dialect=dialect,
2482            **opts,
2483        )
2484
2485    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
2486        """
2487        Set the LIMIT expression.
2488
2489        Example:
2490            >>> Select().from_("tbl").select("x").limit(10).sql()
2491            'SELECT x FROM tbl LIMIT 10'
2492
2493        Args:
2494            expression (str | int | Expression): the SQL code string to parse.
2495                This can also be an integer.
2496                If a `Limit` instance is passed, this is used as-is.
2497                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2498            dialect (str): the dialect used to parse the input expression.
2499            copy (bool): if `False`, modify this expression instance in-place.
2500            opts (kwargs): other options to use to parse the input expressions.
2501
2502        Returns:
2503            Select: the modified expression.
2504        """
2505        return _apply_builder(
2506            expression=expression,
2507            instance=self,
2508            arg="limit",
2509            into=Limit,
2510            prefix="LIMIT",
2511            dialect=dialect,
2512            copy=copy,
2513            **opts,
2514        )
2515
2516    def offset(self, expression, dialect=None, copy=True, **opts) -> Select:
2517        """
2518        Set the OFFSET expression.
2519
2520        Example:
2521            >>> Select().from_("tbl").select("x").offset(10).sql()
2522            'SELECT x FROM tbl OFFSET 10'
2523
2524        Args:
2525            expression (str | int | Expression): the SQL code string to parse.
2526                This can also be an integer.
2527                If a `Offset` instance is passed, this is used as-is.
2528                If another `Expression` instance is passed, it will be wrapped in a `Offset`.
2529            dialect (str): the dialect used to parse the input expression.
2530            copy (bool): if `False`, modify this expression instance in-place.
2531            opts (kwargs): other options to use to parse the input expressions.
2532
2533        Returns:
2534            Select: the modified expression.
2535        """
2536        return _apply_builder(
2537            expression=expression,
2538            instance=self,
2539            arg="offset",
2540            into=Offset,
2541            prefix="OFFSET",
2542            dialect=dialect,
2543            copy=copy,
2544            **opts,
2545        )
2546
2547    def select(
2548        self,
2549        *expressions: ExpOrStr,
2550        append: bool = True,
2551        dialect: DialectType = None,
2552        copy: bool = True,
2553        **opts,
2554    ) -> Select:
2555        """
2556        Append to or set the SELECT expressions.
2557
2558        Example:
2559            >>> Select().select("x", "y").sql()
2560            'SELECT x, y'
2561
2562        Args:
2563            *expressions: the SQL code strings to parse.
2564                If an `Expression` instance is passed, it will be used as-is.
2565            append: if `True`, add to any existing expressions.
2566                Otherwise, this resets the expressions.
2567            dialect: the dialect used to parse the input expressions.
2568            copy: if `False`, modify this expression instance in-place.
2569            opts: other options to use to parse the input expressions.
2570
2571        Returns:
2572            Select: the modified expression.
2573        """
2574        return _apply_list_builder(
2575            *expressions,
2576            instance=self,
2577            arg="expressions",
2578            append=append,
2579            dialect=dialect,
2580            copy=copy,
2581            **opts,
2582        )
2583
2584    def lateral(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2585        """
2586        Append to or set the LATERAL expressions.
2587
2588        Example:
2589            >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
2590            'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
2591
2592        Args:
2593            *expressions (str | Expression): the SQL code strings to parse.
2594                If an `Expression` instance is passed, it will be used as-is.
2595            append (bool): if `True`, add to any existing expressions.
2596                Otherwise, this resets the expressions.
2597            dialect (str): the dialect used to parse the input expressions.
2598            copy (bool): if `False`, modify this expression instance in-place.
2599            opts (kwargs): other options to use to parse the input expressions.
2600
2601        Returns:
2602            Select: the modified expression.
2603        """
2604        return _apply_list_builder(
2605            *expressions,
2606            instance=self,
2607            arg="laterals",
2608            append=append,
2609            into=Lateral,
2610            prefix="LATERAL VIEW",
2611            dialect=dialect,
2612            copy=copy,
2613            **opts,
2614        )
2615
2616    def join(
2617        self,
2618        expression,
2619        on=None,
2620        using=None,
2621        append=True,
2622        join_type=None,
2623        join_alias=None,
2624        dialect=None,
2625        copy=True,
2626        **opts,
2627    ) -> Select:
2628        """
2629        Append to or set the JOIN expressions.
2630
2631        Example:
2632            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
2633            'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
2634
2635            >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
2636            'SELECT 1 FROM a JOIN b USING (x, y, z)'
2637
2638            Use `join_type` to change the type of join:
2639
2640            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
2641            'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
2642
2643        Args:
2644            expression (str | Expression): the SQL code string to parse.
2645                If an `Expression` instance is passed, it will be used as-is.
2646            on (str | Expression): optionally specify the join "on" criteria as a SQL string.
2647                If an `Expression` instance is passed, it will be used as-is.
2648            using (str | Expression): optionally specify the join "using" criteria as a SQL string.
2649                If an `Expression` instance is passed, it will be used as-is.
2650            append (bool): if `True`, add to any existing expressions.
2651                Otherwise, this resets the expressions.
2652            join_type (str): If set, alter the parsed join type
2653            dialect (str): the dialect used to parse the input expressions.
2654            copy (bool): if `False`, modify this expression instance in-place.
2655            opts (kwargs): other options to use to parse the input expressions.
2656
2657        Returns:
2658            Select: the modified expression.
2659        """
2660        parse_args = {"dialect": dialect, **opts}
2661
2662        try:
2663            expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args)
2664        except ParseError:
2665            expression = maybe_parse(expression, into=(Join, Expression), **parse_args)
2666
2667        join = expression if isinstance(expression, Join) else Join(this=expression)
2668
2669        if isinstance(join.this, Select):
2670            join.this.replace(join.this.subquery())
2671
2672        if join_type:
2673            natural: t.Optional[Token]
2674            side: t.Optional[Token]
2675            kind: t.Optional[Token]
2676
2677            natural, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args)  # type: ignore
2678
2679            if natural:
2680                join.set("natural", True)
2681            if side:
2682                join.set("side", side.text)
2683            if kind:
2684                join.set("kind", kind.text)
2685
2686        if on:
2687            on = and_(*ensure_collection(on), dialect=dialect, copy=copy, **opts)
2688            join.set("on", on)
2689
2690        if using:
2691            join = _apply_list_builder(
2692                *ensure_collection(using),
2693                instance=join,
2694                arg="using",
2695                append=append,
2696                copy=copy,
2697                **opts,
2698            )
2699
2700        if join_alias:
2701            join.set("this", alias_(join.this, join_alias, table=True))
2702        return _apply_list_builder(
2703            join,
2704            instance=self,
2705            arg="joins",
2706            append=append,
2707            copy=copy,
2708            **opts,
2709        )
2710
2711    def where(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2712        """
2713        Append to or set the WHERE expressions.
2714
2715        Example:
2716            >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
2717            "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
2718
2719        Args:
2720            *expressions (str | Expression): the SQL code strings to parse.
2721                If an `Expression` instance is passed, it will be used as-is.
2722                Multiple expressions are combined with an AND operator.
2723            append (bool): if `True`, AND the new expressions to any existing expression.
2724                Otherwise, this resets the expression.
2725            dialect (str): the dialect used to parse the input expressions.
2726            copy (bool): if `False`, modify this expression instance in-place.
2727            opts (kwargs): other options to use to parse the input expressions.
2728
2729        Returns:
2730            Select: the modified expression.
2731        """
2732        return _apply_conjunction_builder(
2733            *expressions,
2734            instance=self,
2735            arg="where",
2736            append=append,
2737            into=Where,
2738            dialect=dialect,
2739            copy=copy,
2740            **opts,
2741        )
2742
2743    def having(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2744        """
2745        Append to or set the HAVING expressions.
2746
2747        Example:
2748            >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
2749            'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
2750
2751        Args:
2752            *expressions (str | Expression): the SQL code strings to parse.
2753                If an `Expression` instance is passed, it will be used as-is.
2754                Multiple expressions are combined with an AND operator.
2755            append (bool): if `True`, AND the new expressions to any existing expression.
2756                Otherwise, this resets the expression.
2757            dialect (str): the dialect used to parse the input expressions.
2758            copy (bool): if `False`, modify this expression instance in-place.
2759            opts (kwargs): other options to use to parse the input expressions.
2760
2761        Returns:
2762            Select: the modified expression.
2763        """
2764        return _apply_conjunction_builder(
2765            *expressions,
2766            instance=self,
2767            arg="having",
2768            append=append,
2769            into=Having,
2770            dialect=dialect,
2771            copy=copy,
2772            **opts,
2773        )
2774
2775    def window(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2776        return _apply_list_builder(
2777            *expressions,
2778            instance=self,
2779            arg="windows",
2780            append=append,
2781            into=Window,
2782            dialect=dialect,
2783            copy=copy,
2784            **opts,
2785        )
2786
2787    def qualify(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2788        return _apply_conjunction_builder(
2789            *expressions,
2790            instance=self,
2791            arg="qualify",
2792            append=append,
2793            into=Qualify,
2794            dialect=dialect,
2795            copy=copy,
2796            **opts,
2797        )
2798
2799    def distinct(self, *ons: ExpOrStr, distinct: bool = True, copy: bool = True) -> Select:
2800        """
2801        Set the OFFSET expression.
2802
2803        Example:
2804            >>> Select().from_("tbl").select("x").distinct().sql()
2805            'SELECT DISTINCT x FROM tbl'
2806
2807        Args:
2808            ons: the expressions to distinct on
2809            distinct: whether the Select should be distinct
2810            copy: if `False`, modify this expression instance in-place.
2811
2812        Returns:
2813            Select: the modified expression.
2814        """
2815        instance = _maybe_copy(self, copy)
2816        on = Tuple(expressions=[maybe_parse(on, copy=copy) for on in ons]) if ons else None
2817        instance.set("distinct", Distinct(on=on) if distinct else None)
2818        return instance
2819
2820    def ctas(self, table, properties=None, dialect=None, copy=True, **opts) -> Create:
2821        """
2822        Convert this expression to a CREATE TABLE AS statement.
2823
2824        Example:
2825            >>> Select().select("*").from_("tbl").ctas("x").sql()
2826            'CREATE TABLE x AS SELECT * FROM tbl'
2827
2828        Args:
2829            table (str | Expression): the SQL code string to parse as the table name.
2830                If another `Expression` instance is passed, it will be used as-is.
2831            properties (dict): an optional mapping of table properties
2832            dialect (str): the dialect used to parse the input table.
2833            copy (bool): if `False`, modify this expression instance in-place.
2834            opts (kwargs): other options to use to parse the input table.
2835
2836        Returns:
2837            Create: the CREATE TABLE AS expression
2838        """
2839        instance = _maybe_copy(self, copy)
2840        table_expression = maybe_parse(
2841            table,
2842            into=Table,
2843            dialect=dialect,
2844            **opts,
2845        )
2846        properties_expression = None
2847        if properties:
2848            properties_expression = Properties.from_dict(properties)
2849
2850        return Create(
2851            this=table_expression,
2852            kind="table",
2853            expression=instance,
2854            properties=properties_expression,
2855        )
2856
2857    def lock(self, update: bool = True, copy: bool = True) -> Select:
2858        """
2859        Set the locking read mode for this expression.
2860
2861        Examples:
2862            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
2863            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
2864
2865            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
2866            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
2867
2868        Args:
2869            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
2870            copy: if `False`, modify this expression instance in-place.
2871
2872        Returns:
2873            The modified expression.
2874        """
2875
2876        inst = _maybe_copy(self, copy)
2877        inst.set("lock", Lock(update=update))
2878
2879        return inst
2880
2881    @property
2882    def named_selects(self) -> t.List[str]:
2883        return [e.output_name for e in self.expressions if e.alias_or_name]
2884
2885    @property
2886    def is_star(self) -> bool:
2887        return any(expression.is_star for expression in self.expressions)
2888
2889    @property
2890    def selects(self) -> t.List[Expression]:
2891        return self.expressions
2892
2893
2894class Subquery(DerivedTable, Unionable):
2895    arg_types = {
2896        "this": True,
2897        "alias": False,
2898        "with": False,
2899        **QUERY_MODIFIERS,
2900    }
2901
2902    def unnest(self):
2903        """
2904        Returns the first non subquery.
2905        """
2906        expression = self
2907        while isinstance(expression, Subquery):
2908            expression = expression.this
2909        return expression
2910
2911    @property
2912    def is_star(self) -> bool:
2913        return self.this.is_star
2914
2915    @property
2916    def output_name(self):
2917        return self.alias
2918
2919
2920class TableSample(Expression):
2921    arg_types = {
2922        "this": False,
2923        "method": False,
2924        "bucket_numerator": False,
2925        "bucket_denominator": False,
2926        "bucket_field": False,
2927        "percent": False,
2928        "rows": False,
2929        "size": False,
2930        "seed": False,
2931        "kind": False,
2932    }
2933
2934
2935class Tag(Expression):
2936    """Tags are used for generating arbitrary sql like SELECT <span>x</span>."""
2937
2938    arg_types = {
2939        "this": False,
2940        "prefix": False,
2941        "postfix": False,
2942    }
2943
2944
2945class Pivot(Expression):
2946    arg_types = {
2947        "this": False,
2948        "alias": False,
2949        "expressions": True,
2950        "field": True,
2951        "unpivot": True,
2952        "columns": False,
2953    }
2954
2955
2956class Window(Expression):
2957    arg_types = {
2958        "this": True,
2959        "partition_by": False,
2960        "order": False,
2961        "spec": False,
2962        "alias": False,
2963        "over": False,
2964        "first": False,
2965    }
2966
2967
2968class WindowSpec(Expression):
2969    arg_types = {
2970        "kind": False,
2971        "start": False,
2972        "start_side": False,
2973        "end": False,
2974        "end_side": False,
2975    }
2976
2977
2978class Where(Expression):
2979    pass
2980
2981
2982class Star(Expression):
2983    arg_types = {"except": False, "replace": False}
2984
2985    @property
2986    def name(self) -> str:
2987        return "*"
2988
2989    @property
2990    def output_name(self):
2991        return self.name
2992
2993
2994class Parameter(Expression):
2995    arg_types = {"this": True, "wrapped": False}
2996
2997
2998class SessionParameter(Expression):
2999    arg_types = {"this": True, "kind": False}
3000
3001
3002class Placeholder(Expression):
3003    arg_types = {"this": False}
3004
3005
3006class Null(Condition):
3007    arg_types: t.Dict[str, t.Any] = {}
3008
3009    @property
3010    def name(self) -> str:
3011        return "NULL"
3012
3013
3014class Boolean(Condition):
3015    pass
3016
3017
3018class DataTypeSize(Expression):
3019    arg_types = {"this": True, "expression": False}
3020
3021
3022class DataType(Expression):
3023    arg_types = {
3024        "this": True,
3025        "expressions": False,
3026        "nested": False,
3027        "values": False,
3028        "prefix": False,
3029    }
3030
3031    class Type(AutoName):
3032        CHAR = auto()
3033        NCHAR = auto()
3034        VARCHAR = auto()
3035        NVARCHAR = auto()
3036        TEXT = auto()
3037        MEDIUMTEXT = auto()
3038        LONGTEXT = auto()
3039        MEDIUMBLOB = auto()
3040        LONGBLOB = auto()
3041        BINARY = auto()
3042        VARBINARY = auto()
3043        INT = auto()
3044        UINT = auto()
3045        TINYINT = auto()
3046        UTINYINT = auto()
3047        SMALLINT = auto()
3048        USMALLINT = auto()
3049        BIGINT = auto()
3050        UBIGINT = auto()
3051        INT128 = auto()
3052        UINT128 = auto()
3053        INT256 = auto()
3054        UINT256 = auto()
3055        FLOAT = auto()
3056        DOUBLE = auto()
3057        DECIMAL = auto()
3058        BIGDECIMAL = auto()
3059        BIT = auto()
3060        BOOLEAN = auto()
3061        JSON = auto()
3062        JSONB = auto()
3063        INTERVAL = auto()
3064        TIME = auto()
3065        TIMESTAMP = auto()
3066        TIMESTAMPTZ = auto()
3067        TIMESTAMPLTZ = auto()
3068        DATE = auto()
3069        DATETIME = auto()
3070        DATETIME64 = auto()
3071        ARRAY = auto()
3072        MAP = auto()
3073        UUID = auto()
3074        GEOGRAPHY = auto()
3075        GEOMETRY = auto()
3076        STRUCT = auto()
3077        NULLABLE = auto()
3078        HLLSKETCH = auto()
3079        HSTORE = auto()
3080        SUPER = auto()
3081        SERIAL = auto()
3082        SMALLSERIAL = auto()
3083        BIGSERIAL = auto()
3084        XML = auto()
3085        UNIQUEIDENTIFIER = auto()
3086        MONEY = auto()
3087        SMALLMONEY = auto()
3088        ROWVERSION = auto()
3089        IMAGE = auto()
3090        VARIANT = auto()
3091        OBJECT = auto()
3092        INET = auto()
3093        NULL = auto()
3094        UNKNOWN = auto()  # Sentinel value, useful for type annotation
3095
3096    TEXT_TYPES = {
3097        Type.CHAR,
3098        Type.NCHAR,
3099        Type.VARCHAR,
3100        Type.NVARCHAR,
3101        Type.TEXT,
3102    }
3103
3104    INTEGER_TYPES = {
3105        Type.INT,
3106        Type.TINYINT,
3107        Type.SMALLINT,
3108        Type.BIGINT,
3109        Type.INT128,
3110        Type.INT256,
3111    }
3112
3113    FLOAT_TYPES = {
3114        Type.FLOAT,
3115        Type.DOUBLE,
3116    }
3117
3118    NUMERIC_TYPES = {*INTEGER_TYPES, *FLOAT_TYPES}
3119
3120    TEMPORAL_TYPES = {
3121        Type.TIMESTAMP,
3122        Type.TIMESTAMPTZ,
3123        Type.TIMESTAMPLTZ,
3124        Type.DATE,
3125        Type.DATETIME,
3126        Type.DATETIME64,
3127    }
3128
3129    @classmethod
3130    def build(
3131        cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs
3132    ) -> DataType:
3133        from sqlglot import parse_one
3134
3135        if isinstance(dtype, str):
3136            if dtype.upper() in cls.Type.__members__:
3137                data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[dtype.upper()])
3138            else:
3139                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
3140            if data_type_exp is None:
3141                raise ValueError(f"Unparsable data type value: {dtype}")
3142        elif isinstance(dtype, DataType.Type):
3143            data_type_exp = DataType(this=dtype)
3144        elif isinstance(dtype, DataType):
3145            return dtype
3146        else:
3147            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
3148        return DataType(**{**data_type_exp.args, **kwargs})
3149
3150    def is_type(self, dtype: DataType.Type) -> bool:
3151        return self.this == dtype
3152
3153
3154# https://www.postgresql.org/docs/15/datatype-pseudo.html
3155class PseudoType(Expression):
3156    pass
3157
3158
3159# WHERE x <OP> EXISTS|ALL|ANY|SOME(SELECT ...)
3160class SubqueryPredicate(Predicate):
3161    pass
3162
3163
3164class All(SubqueryPredicate):
3165    pass
3166
3167
3168class Any(SubqueryPredicate):
3169    pass
3170
3171
3172class Exists(SubqueryPredicate):
3173    pass
3174
3175
3176# Commands to interact with the databases or engines. For most of the command
3177# expressions we parse whatever comes after the command's name as a string.
3178class Command(Expression):
3179    arg_types = {"this": True, "expression": False}
3180
3181
3182class Transaction(Expression):
3183    arg_types = {"this": False, "modes": False}
3184
3185
3186class Commit(Expression):
3187    arg_types = {"chain": False}
3188
3189
3190class Rollback(Expression):
3191    arg_types = {"savepoint": False}
3192
3193
3194class AlterTable(Expression):
3195    arg_types = {"this": True, "actions": True, "exists": False}
3196
3197
3198class AddConstraint(Expression):
3199    arg_types = {"this": False, "expression": False, "enforced": False}
3200
3201
3202class DropPartition(Expression):
3203    arg_types = {"expressions": True, "exists": False}
3204
3205
3206# Binary expressions like (ADD a b)
3207class Binary(Condition):
3208    arg_types = {"this": True, "expression": True}
3209
3210    @property
3211    def left(self):
3212        return self.this
3213
3214    @property
3215    def right(self):
3216        return self.expression
3217
3218
3219class Add(Binary):
3220    pass
3221
3222
3223class Connector(Binary):
3224    pass
3225
3226
3227class And(Connector):
3228    pass
3229
3230
3231class Or(Connector):
3232    pass
3233
3234
3235class BitwiseAnd(Binary):
3236    pass
3237
3238
3239class BitwiseLeftShift(Binary):
3240    pass
3241
3242
3243class BitwiseOr(Binary):
3244    pass
3245
3246
3247class BitwiseRightShift(Binary):
3248    pass
3249
3250
3251class BitwiseXor(Binary):
3252    pass
3253
3254
3255class Div(Binary):
3256    pass
3257
3258
3259class Overlaps(Binary):
3260    pass
3261
3262
3263class Dot(Binary):
3264    @property
3265    def name(self) -> str:
3266        return self.expression.name
3267
3268    @classmethod
3269    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3270        """Build a Dot object with a sequence of expressions."""
3271        if len(expressions) < 2:
3272            raise ValueError(f"Dot requires >= 2 expressions.")
3273
3274        a, b, *expressions = expressions
3275        dot = Dot(this=a, expression=b)
3276
3277        for expression in expressions:
3278            dot = Dot(this=dot, expression=expression)
3279
3280        return dot
3281
3282
3283class DPipe(Binary):
3284    pass
3285
3286
3287class EQ(Binary, Predicate):
3288    pass
3289
3290
3291class NullSafeEQ(Binary, Predicate):
3292    pass
3293
3294
3295class NullSafeNEQ(Binary, Predicate):
3296    pass
3297
3298
3299class Distance(Binary):
3300    pass
3301
3302
3303class Escape(Binary):
3304    pass
3305
3306
3307class Glob(Binary, Predicate):
3308    pass
3309
3310
3311class GT(Binary, Predicate):
3312    pass
3313
3314
3315class GTE(Binary, Predicate):
3316    pass
3317
3318
3319class ILike(Binary, Predicate):
3320    pass
3321
3322
3323class ILikeAny(Binary, Predicate):
3324    pass
3325
3326
3327class IntDiv(Binary):
3328    pass
3329
3330
3331class Is(Binary, Predicate):
3332    pass
3333
3334
3335class Kwarg(Binary):
3336    """Kwarg in special functions like func(kwarg => y)."""
3337
3338
3339class Like(Binary, Predicate):
3340    pass
3341
3342
3343class LikeAny(Binary, Predicate):
3344    pass
3345
3346
3347class LT(Binary, Predicate):
3348    pass
3349
3350
3351class LTE(Binary, Predicate):
3352    pass
3353
3354
3355class Mod(Binary):
3356    pass
3357
3358
3359class Mul(Binary):
3360    pass
3361
3362
3363class NEQ(Binary, Predicate):
3364    pass
3365
3366
3367class SimilarTo(Binary, Predicate):
3368    pass
3369
3370
3371class Slice(Binary):
3372    arg_types = {"this": False, "expression": False}
3373
3374
3375class Sub(Binary):
3376    pass
3377
3378
3379class ArrayOverlaps(Binary):
3380    pass
3381
3382
3383# Unary Expressions
3384# (NOT a)
3385class Unary(Condition):
3386    pass
3387
3388
3389class BitwiseNot(Unary):
3390    pass
3391
3392
3393class Not(Unary):
3394    pass
3395
3396
3397class Paren(Unary):
3398    arg_types = {"this": True, "with": False}
3399
3400
3401class Neg(Unary):
3402    pass
3403
3404
3405class Alias(Expression):
3406    arg_types = {"this": True, "alias": False}
3407
3408    @property
3409    def output_name(self):
3410        return self.alias
3411
3412
3413class Aliases(Expression):
3414    arg_types = {"this": True, "expressions": True}
3415
3416    @property
3417    def aliases(self):
3418        return self.expressions
3419
3420
3421class AtTimeZone(Expression):
3422    arg_types = {"this": True, "zone": True}
3423
3424
3425class Between(Predicate):
3426    arg_types = {"this": True, "low": True, "high": True}
3427
3428
3429class Bracket(Condition):
3430    arg_types = {"this": True, "expressions": True}
3431
3432
3433class Distinct(Expression):
3434    arg_types = {"expressions": False, "on": False}
3435
3436
3437class In(Predicate):
3438    arg_types = {
3439        "this": True,
3440        "expressions": False,
3441        "query": False,
3442        "unnest": False,
3443        "field": False,
3444        "is_global": False,
3445    }
3446
3447
3448class TimeUnit(Expression):
3449    """Automatically converts unit arg into a var."""
3450
3451    arg_types = {"unit": False}
3452
3453    def __init__(self, **args):
3454        unit = args.get("unit")
3455        if isinstance(unit, (Column, Literal)):
3456            args["unit"] = Var(this=unit.name)
3457        elif isinstance(unit, Week):
3458            unit.set("this", Var(this=unit.this.name))
3459        super().__init__(**args)
3460
3461
3462class Interval(TimeUnit):
3463    arg_types = {"this": False, "unit": False}
3464
3465
3466class IgnoreNulls(Expression):
3467    pass
3468
3469
3470class RespectNulls(Expression):
3471    pass
3472
3473
3474# Functions
3475class Func(Condition):
3476    """
3477    The base class for all function expressions.
3478
3479    Attributes:
3480        is_var_len_args (bool): if set to True the last argument defined in arg_types will be
3481            treated as a variable length argument and the argument's value will be stored as a list.
3482        _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items)
3483            for this function expression. These values are used to map this node to a name during parsing
3484            as well as to provide the function's name during SQL string generation. By default the SQL
3485            name is set to the expression's class name transformed to snake case.
3486    """
3487
3488    is_var_len_args = False
3489
3490    @classmethod
3491    def from_arg_list(cls, args):
3492        if cls.is_var_len_args:
3493            all_arg_keys = list(cls.arg_types)
3494            # If this function supports variable length argument treat the last argument as such.
3495            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3496            num_non_var = len(non_var_len_arg_keys)
3497
3498            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3499            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3500        else:
3501            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3502
3503        return cls(**args_dict)
3504
3505    @classmethod
3506    def sql_names(cls):
3507        if cls is Func:
3508            raise NotImplementedError(
3509                "SQL name is only supported by concrete function implementations"
3510            )
3511        if "_sql_names" not in cls.__dict__:
3512            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3513        return cls._sql_names
3514
3515    @classmethod
3516    def sql_name(cls):
3517        return cls.sql_names()[0]
3518
3519    @classmethod
3520    def default_parser_mappings(cls):
3521        return {name: cls.from_arg_list for name in cls.sql_names()}
3522
3523
3524class AggFunc(Func):
3525    pass
3526
3527
3528class Abs(Func):
3529    pass
3530
3531
3532class Anonymous(Func):
3533    arg_types = {"this": True, "expressions": False}
3534    is_var_len_args = True
3535
3536
3537# https://docs.snowflake.com/en/sql-reference/functions/hll
3538# https://docs.aws.amazon.com/redshift/latest/dg/r_HLL_function.html
3539class Hll(AggFunc):
3540    arg_types = {"this": True, "expressions": False}
3541    is_var_len_args = True
3542
3543
3544class ApproxDistinct(AggFunc):
3545    arg_types = {"this": True, "accuracy": False}
3546
3547
3548class Array(Func):
3549    arg_types = {"expressions": False}
3550    is_var_len_args = True
3551
3552
3553# https://docs.snowflake.com/en/sql-reference/functions/to_char
3554class ToChar(Func):
3555    arg_types = {"this": True, "format": False}
3556
3557
3558class GenerateSeries(Func):
3559    arg_types = {"start": True, "end": True, "step": False}
3560
3561
3562class ArrayAgg(AggFunc):
3563    pass
3564
3565
3566class ArrayAll(Func):
3567    arg_types = {"this": True, "expression": True}
3568
3569
3570class ArrayAny(Func):
3571    arg_types = {"this": True, "expression": True}
3572
3573
3574class ArrayConcat(Func):
3575    arg_types = {"this": True, "expressions": False}
3576    is_var_len_args = True
3577
3578
3579class ArrayContains(Binary, Func):
3580    pass
3581
3582
3583class ArrayContained(Binary):
3584    pass
3585
3586
3587class ArrayFilter(Func):
3588    arg_types = {"this": True, "expression": True}
3589    _sql_names = ["FILTER", "ARRAY_FILTER"]
3590
3591
3592class ArrayJoin(Func):
3593    arg_types = {"this": True, "expression": True, "null": False}
3594
3595
3596class ArraySize(Func):
3597    arg_types = {"this": True, "expression": False}
3598
3599
3600class ArraySort(Func):
3601    arg_types = {"this": True, "expression": False}
3602
3603
3604class ArraySum(Func):
3605    pass
3606
3607
3608class ArrayUnionAgg(AggFunc):
3609    pass
3610
3611
3612class Avg(AggFunc):
3613    pass
3614
3615
3616class AnyValue(AggFunc):
3617    pass
3618
3619
3620class Case(Func):
3621    arg_types = {"this": False, "ifs": True, "default": False}
3622
3623    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
3624        instance = _maybe_copy(self, copy)
3625        instance.append(
3626            "ifs",
3627            If(
3628                this=maybe_parse(condition, copy=copy, **opts),
3629                true=maybe_parse(then, copy=copy, **opts),
3630            ),
3631        )
3632        return instance
3633
3634    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
3635        instance = _maybe_copy(self, copy)
3636        instance.set("default", maybe_parse(condition, copy=copy, **opts))
3637        return instance
3638
3639
3640class Cast(Func):
3641    arg_types = {"this": True, "to": True}
3642
3643    @property
3644    def name(self) -> str:
3645        return self.this.name
3646
3647    @property
3648    def to(self):
3649        return self.args["to"]
3650
3651    @property
3652    def output_name(self):
3653        return self.name
3654
3655    def is_type(self, dtype: DataType.Type) -> bool:
3656        return self.to.is_type(dtype)
3657
3658
3659class Collate(Binary):
3660    pass
3661
3662
3663class TryCast(Cast):
3664    pass
3665
3666
3667class Ceil(Func):
3668    arg_types = {"this": True, "decimals": False}
3669    _sql_names = ["CEIL", "CEILING"]
3670
3671
3672class Coalesce(Func):
3673    arg_types = {"this": True, "expressions": False}
3674    is_var_len_args = True
3675
3676
3677class Concat(Func):
3678    arg_types = {"expressions": True}
3679    is_var_len_args = True
3680
3681
3682class ConcatWs(Concat):
3683    _sql_names = ["CONCAT_WS"]
3684
3685
3686class Count(AggFunc):
3687    arg_types = {"this": False}
3688
3689
3690class CountIf(AggFunc):
3691    pass
3692
3693
3694class CurrentDate(Func):
3695    arg_types = {"this": False}
3696
3697
3698class CurrentDatetime(Func):
3699    arg_types = {"this": False}
3700
3701
3702class CurrentTime(Func):
3703    arg_types = {"this": False}
3704
3705
3706class CurrentTimestamp(Func):
3707    arg_types = {"this": False}
3708
3709
3710class CurrentUser(Func):
3711    arg_types = {"this": False}
3712
3713
3714class DateAdd(Func, TimeUnit):
3715    arg_types = {"this": True, "expression": True, "unit": False}
3716
3717
3718class DateSub(Func, TimeUnit):
3719    arg_types = {"this": True, "expression": True, "unit": False}
3720
3721
3722class DateDiff(Func, TimeUnit):
3723    _sql_names = ["DATEDIFF", "DATE_DIFF"]
3724    arg_types = {"this": True, "expression": True, "unit": False}
3725
3726
3727class DateTrunc(Func):
3728    arg_types = {"unit": True, "this": True, "zone": False}
3729
3730
3731class DatetimeAdd(Func, TimeUnit):
3732    arg_types = {"this": True, "expression": True, "unit": False}
3733
3734
3735class DatetimeSub(Func, TimeUnit):
3736    arg_types = {"this": True, "expression": True, "unit": False}
3737
3738
3739class DatetimeDiff(Func, TimeUnit):
3740    arg_types = {"this": True, "expression": True, "unit": False}
3741
3742
3743class DatetimeTrunc(Func, TimeUnit):
3744    arg_types = {"this": True, "unit": True, "zone": False}
3745
3746
3747class DayOfWeek(Func):
3748    _sql_names = ["DAY_OF_WEEK", "DAYOFWEEK"]
3749
3750
3751class DayOfMonth(Func):
3752    _sql_names = ["DAY_OF_MONTH", "DAYOFMONTH"]
3753
3754
3755class DayOfYear(Func):
3756    _sql_names = ["DAY_OF_YEAR", "DAYOFYEAR"]
3757
3758
3759class WeekOfYear(Func):
3760    _sql_names = ["WEEK_OF_YEAR", "WEEKOFYEAR"]
3761
3762
3763class LastDateOfMonth(Func):
3764    pass
3765
3766
3767class Extract(Func):
3768    arg_types = {"this": True, "expression": True}
3769
3770
3771class TimestampAdd(Func, TimeUnit):
3772    arg_types = {"this": True, "expression": True, "unit": False}
3773
3774
3775class TimestampSub(Func, TimeUnit):
3776    arg_types = {"this": True, "expression": True, "unit": False}
3777
3778
3779class TimestampDiff(Func, TimeUnit):
3780    arg_types = {"this": True, "expression": True, "unit": False}
3781
3782
3783class TimestampTrunc(Func, TimeUnit):
3784    arg_types = {"this": True, "unit": True, "zone": False}
3785
3786
3787class TimeAdd(Func, TimeUnit):
3788    arg_types = {"this": True, "expression": True, "unit": False}
3789
3790
3791class TimeSub(Func, TimeUnit):
3792    arg_types = {"this": True, "expression": True, "unit": False}
3793
3794
3795class TimeDiff(Func, TimeUnit):
3796    arg_types = {"this": True, "expression": True, "unit": False}
3797
3798
3799class TimeTrunc(Func, TimeUnit):
3800    arg_types = {"this": True, "unit": True, "zone": False}
3801
3802
3803class DateFromParts(Func):
3804    _sql_names = ["DATEFROMPARTS"]
3805    arg_types = {"year": True, "month": True, "day": True}
3806
3807
3808class DateStrToDate(Func):
3809    pass
3810
3811
3812class DateToDateStr(Func):
3813    pass
3814
3815
3816class DateToDi(Func):
3817    pass
3818
3819
3820class Day(Func):
3821    pass
3822
3823
3824class Decode(Func):
3825    arg_types = {"this": True, "charset": True, "replace": False}
3826
3827
3828class DiToDate(Func):
3829    pass
3830
3831
3832class Encode(Func):
3833    arg_types = {"this": True, "charset": True}
3834
3835
3836class Exp(Func):
3837    pass
3838
3839
3840class Explode(Func):
3841    pass
3842
3843
3844class ExponentialTimeDecayedAvg(AggFunc):
3845    arg_types = {"this": True, "time": False, "decay": False}
3846
3847
3848class Floor(Func):
3849    arg_types = {"this": True, "decimals": False}
3850
3851
3852class FromBase64(Func):
3853    pass
3854
3855
3856class ToBase64(Func):
3857    pass
3858
3859
3860class Greatest(Func):
3861    arg_types = {"this": True, "expressions": False}
3862    is_var_len_args = True
3863
3864
3865class GroupConcat(Func):
3866    arg_types = {"this": True, "separator": False}
3867
3868
3869class GroupUniqArray(AggFunc):
3870    arg_types = {"this": True, "size": False}
3871
3872
3873class Hex(Func):
3874    pass
3875
3876
3877class Histogram(AggFunc):
3878    arg_types = {"this": True, "bins": False}
3879
3880
3881class If(Func):
3882    arg_types = {"this": True, "true": True, "false": False}
3883
3884
3885class IfNull(Func):
3886    arg_types = {"this": True, "expression": False}
3887    _sql_names = ["IFNULL", "NVL"]
3888
3889
3890class Initcap(Func):
3891    pass
3892
3893
3894class JSONKeyValue(Expression):
3895    arg_types = {"this": True, "expression": True}
3896
3897
3898class JSONObject(Func):
3899    arg_types = {
3900        "expressions": False,
3901        "null_handling": False,
3902        "unique_keys": False,
3903        "return_type": False,
3904        "format_json": False,
3905        "encoding": False,
3906    }
3907
3908
3909class OpenJSONColumnDef(Expression):
3910    arg_types = {"this": True, "kind": True, "path": False, "as_json": False}
3911
3912
3913class OpenJSON(Func):
3914    arg_types = {"this": True, "path": False, "expressions": False}
3915
3916
3917class JSONBContains(Binary):
3918    _sql_names = ["JSONB_CONTAINS"]
3919
3920
3921class JSONExtract(Binary, Func):
3922    _sql_names = ["JSON_EXTRACT"]
3923
3924
3925class JSONExtractScalar(JSONExtract):
3926    _sql_names = ["JSON_EXTRACT_SCALAR"]
3927
3928
3929class JSONBExtract(JSONExtract):
3930    _sql_names = ["JSONB_EXTRACT"]
3931
3932
3933class JSONBExtractScalar(JSONExtract):
3934    _sql_names = ["JSONB_EXTRACT_SCALAR"]
3935
3936
3937class JSONFormat(Func):
3938    arg_types = {"this": False, "options": False}
3939    _sql_names = ["JSON_FORMAT"]
3940
3941
3942class Least(Func):
3943    arg_types = {"expressions": False}
3944    is_var_len_args = True
3945
3946
3947class Length(Func):
3948    pass
3949
3950
3951class Levenshtein(Func):
3952    arg_types = {
3953        "this": True,
3954        "expression": False,
3955        "ins_cost": False,
3956        "del_cost": False,
3957        "sub_cost": False,
3958    }
3959
3960
3961class Ln(Func):
3962    pass
3963
3964
3965class Log(Func):
3966    arg_types = {"this": True, "expression": False}
3967
3968
3969class Log2(Func):
3970    pass
3971
3972
3973class Log10(Func):
3974    pass
3975
3976
3977class LogicalOr(AggFunc):
3978    _sql_names = ["LOGICAL_OR", "BOOL_OR", "BOOLOR_AGG"]
3979
3980
3981class LogicalAnd(AggFunc):
3982    _sql_names = ["LOGICAL_AND", "BOOL_AND", "BOOLAND_AGG"]
3983
3984
3985class Lower(Func):
3986    _sql_names = ["LOWER", "LCASE"]
3987
3988
3989class Map(Func):
3990    arg_types = {"keys": False, "values": False}
3991
3992
3993class StarMap(Func):
3994    pass
3995
3996
3997class VarMap(Func):
3998    arg_types = {"keys": True, "values": True}
3999    is_var_len_args = True
4000
4001
4002# https://dev.mysql.com/doc/refman/8.0/en/fulltext-search.html
4003class MatchAgainst(Func):
4004    arg_types = {"this": True, "expressions": True, "modifier": False}
4005
4006
4007class Max(AggFunc):
4008    arg_types = {"this": True, "expressions": False}
4009    is_var_len_args = True
4010
4011
4012class MD5(Func):
4013    _sql_names = ["MD5"]
4014
4015
4016class Min(AggFunc):
4017    arg_types = {"this": True, "expressions": False}
4018    is_var_len_args = True
4019
4020
4021class Month(Func):
4022    pass
4023
4024
4025class Nvl2(Func):
4026    arg_types = {"this": True, "true": True, "false": False}
4027
4028
4029class Posexplode(Func):
4030    pass
4031
4032
4033class Pow(Binary, Func):
4034    _sql_names = ["POWER", "POW"]
4035
4036
4037class PercentileCont(AggFunc):
4038    arg_types = {"this": True, "expression": False}
4039
4040
4041class PercentileDisc(AggFunc):
4042    arg_types = {"this": True, "expression": False}
4043
4044
4045class Quantile(AggFunc):
4046    arg_types = {"this": True, "quantile": True}
4047
4048
4049# Clickhouse-specific:
4050# https://clickhouse.com/docs/en/sql-reference/aggregate-functions/reference/quantiles/#quantiles
4051class Quantiles(AggFunc):
4052    arg_types = {"parameters": True, "expressions": True}
4053    is_var_len_args = True
4054
4055
4056class QuantileIf(AggFunc):
4057    arg_types = {"parameters": True, "expressions": True}
4058
4059
4060class ApproxQuantile(Quantile):
4061    arg_types = {"this": True, "quantile": True, "accuracy": False, "weight": False}
4062
4063
4064class RangeN(Func):
4065    arg_types = {"this": True, "expressions": True, "each": False}
4066
4067
4068class ReadCSV(Func):
4069    _sql_names = ["READ_CSV"]
4070    is_var_len_args = True
4071    arg_types = {"this": True, "expressions": False}
4072
4073
4074class Reduce(Func):
4075    arg_types = {"this": True, "initial": True, "merge": True, "finish": False}
4076
4077
4078class RegexpExtract(Func):
4079    arg_types = {
4080        "this": True,
4081        "expression": True,
4082        "position": False,
4083        "occurrence": False,
4084        "group": False,
4085    }
4086
4087
4088class RegexpLike(Func):
4089    arg_types = {"this": True, "expression": True, "flag": False}
4090
4091
4092class RegexpILike(Func):
4093    arg_types = {"this": True, "expression": True, "flag": False}
4094
4095
4096# https://spark.apache.org/docs/latest/api/python/reference/pyspark.sql/api/pyspark.sql.functions.split.html
4097# limit is the number of times a pattern is applied
4098class RegexpSplit(Func):
4099    arg_types = {"this": True, "expression": True, "limit": False}
4100
4101
4102class Repeat(Func):
4103    arg_types = {"this": True, "times": True}
4104
4105
4106class Round(Func):
4107    arg_types = {"this": True, "decimals": False}
4108
4109
4110class RowNumber(Func):
4111    arg_types: t.Dict[str, t.Any] = {}
4112
4113
4114class SafeDivide(Func):
4115    arg_types = {"this": True, "expression": True}
4116
4117
4118class SetAgg(AggFunc):
4119    pass
4120
4121
4122class SHA(Func):
4123    _sql_names = ["SHA", "SHA1"]
4124
4125
4126class SHA2(Func):
4127    _sql_names = ["SHA2"]
4128    arg_types = {"this": True, "length": False}
4129
4130
4131class SortArray(Func):
4132    arg_types = {"this": True, "asc": False}
4133
4134
4135class Split(Func):
4136    arg_types = {"this": True, "expression": True, "limit": False}
4137
4138
4139# Start may be omitted in the case of postgres
4140# https://www.postgresql.org/docs/9.1/functions-string.html @ Table 9-6
4141class Substring(Func):
4142    arg_types = {"this": True, "start": False, "length": False}
4143
4144
4145class StandardHash(Func):
4146    arg_types = {"this": True, "expression": False}
4147
4148
4149class StrPosition(Func):
4150    arg_types = {
4151        "this": True,
4152        "substr": True,
4153        "position": False,
4154        "instance": False,
4155    }
4156
4157
4158class StrToDate(Func):
4159    arg_types = {"this": True, "format": True}
4160
4161
4162class StrToTime(Func):
4163    arg_types = {"this": True, "format": True}
4164
4165
4166# Spark allows unix_timestamp()
4167# https://spark.apache.org/docs/3.1.3/api/python/reference/api/pyspark.sql.functions.unix_timestamp.html
4168class StrToUnix(Func):
4169    arg_types = {"this": False, "format": False}
4170
4171
4172class NumberToStr(Func):
4173    arg_types = {"this": True, "format": True}
4174
4175
4176class Struct(Func):
4177    arg_types = {"expressions": True}
4178    is_var_len_args = True
4179
4180
4181class StructExtract(Func):
4182    arg_types = {"this": True, "expression": True}
4183
4184
4185class Sum(AggFunc):
4186    pass
4187
4188
4189class Sqrt(Func):
4190    pass
4191
4192
4193class Stddev(AggFunc):
4194    pass
4195
4196
4197class StddevPop(AggFunc):
4198    pass
4199
4200
4201class StddevSamp(AggFunc):
4202    pass
4203
4204
4205class TimeToStr(Func):
4206    arg_types = {"this": True, "format": True}
4207
4208
4209class TimeToTimeStr(Func):
4210    pass
4211
4212
4213class TimeToUnix(Func):
4214    pass
4215
4216
4217class TimeStrToDate(Func):
4218    pass
4219
4220
4221class TimeStrToTime(Func):
4222    pass
4223
4224
4225class TimeStrToUnix(Func):
4226    pass
4227
4228
4229class Trim(Func):
4230    arg_types = {
4231        "this": True,
4232        "expression": False,
4233        "position": False,
4234        "collation": False,
4235    }
4236
4237
4238class TsOrDsAdd(Func, TimeUnit):
4239    arg_types = {"this": True, "expression": True, "unit": False}
4240
4241
4242class TsOrDsToDateStr(Func):
4243    pass
4244
4245
4246class TsOrDsToDate(Func):
4247    arg_types = {"this": True, "format": False}
4248
4249
4250class TsOrDiToDi(Func):
4251    pass
4252
4253
4254class Unhex(Func):
4255    pass
4256
4257
4258class UnixToStr(Func):
4259    arg_types = {"this": True, "format": False}
4260
4261
4262# https://prestodb.io/docs/current/functions/datetime.html
4263# presto has weird zone/hours/minutes
4264class UnixToTime(Func):
4265    arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False}
4266
4267    SECONDS = Literal.string("seconds")
4268    MILLIS = Literal.string("millis")
4269    MICROS = Literal.string("micros")
4270
4271
4272class UnixToTimeStr(Func):
4273    pass
4274
4275
4276class Upper(Func):
4277    _sql_names = ["UPPER", "UCASE"]
4278
4279
4280class Variance(AggFunc):
4281    _sql_names = ["VARIANCE", "VARIANCE_SAMP", "VAR_SAMP"]
4282
4283
4284class VariancePop(AggFunc):
4285    _sql_names = ["VARIANCE_POP", "VAR_POP"]
4286
4287
4288class Week(Func):
4289    arg_types = {"this": True, "mode": False}
4290
4291
4292class XMLTable(Func):
4293    arg_types = {"this": True, "passing": False, "columns": False, "by_ref": False}
4294
4295
4296class Year(Func):
4297    pass
4298
4299
4300class Use(Expression):
4301    arg_types = {"this": True, "kind": False}
4302
4303
4304class Merge(Expression):
4305    arg_types = {"this": True, "using": True, "on": True, "expressions": True}
4306
4307
4308class When(Func):
4309    arg_types = {"matched": True, "source": False, "condition": False, "then": True}
4310
4311
4312# https://docs.oracle.com/javadb/10.8.3.0/ref/rrefsqljnextvaluefor.html
4313# https://learn.microsoft.com/en-us/sql/t-sql/functions/next-value-for-transact-sql?view=sql-server-ver16
4314class NextValueFor(Func):
4315    arg_types = {"this": True, "order": False}
4316
4317
4318def _norm_arg(arg):
4319    return arg.lower() if type(arg) is str else arg
4320
4321
4322ALL_FUNCTIONS = subclasses(__name__, Func, (AggFunc, Anonymous, Func))
4323
4324
4325# Helpers
4326@t.overload
4327def maybe_parse(
4328    sql_or_expression: ExpOrStr,
4329    *,
4330    into: t.Type[E],
4331    dialect: DialectType = None,
4332    prefix: t.Optional[str] = None,
4333    copy: bool = False,
4334    **opts,
4335) -> E:
4336    ...
4337
4338
4339@t.overload
4340def maybe_parse(
4341    sql_or_expression: str | E,
4342    *,
4343    into: t.Optional[IntoType] = None,
4344    dialect: DialectType = None,
4345    prefix: t.Optional[str] = None,
4346    copy: bool = False,
4347    **opts,
4348) -> E:
4349    ...
4350
4351
4352def maybe_parse(
4353    sql_or_expression: ExpOrStr,
4354    *,
4355    into: t.Optional[IntoType] = None,
4356    dialect: DialectType = None,
4357    prefix: t.Optional[str] = None,
4358    copy: bool = False,
4359    **opts,
4360) -> Expression:
4361    """Gracefully handle a possible string or expression.
4362
4363    Example:
4364        >>> maybe_parse("1")
4365        (LITERAL this: 1, is_string: False)
4366        >>> maybe_parse(to_identifier("x"))
4367        (IDENTIFIER this: x, quoted: False)
4368
4369    Args:
4370        sql_or_expression: the SQL code string or an expression
4371        into: the SQLGlot Expression to parse into
4372        dialect: the dialect used to parse the input expressions (in the case that an
4373            input expression is a SQL string).
4374        prefix: a string to prefix the sql with before it gets parsed
4375            (automatically includes a space)
4376        copy: whether or not to copy the expression.
4377        **opts: other options to use to parse the input expressions (again, in the case
4378            that an input expression is a SQL string).
4379
4380    Returns:
4381        Expression: the parsed or given expression.
4382    """
4383    if isinstance(sql_or_expression, Expression):
4384        if copy:
4385            return sql_or_expression.copy()
4386        return sql_or_expression
4387
4388    import sqlglot
4389
4390    sql = str(sql_or_expression)
4391    if prefix:
4392        sql = f"{prefix} {sql}"
4393    return sqlglot.parse_one(sql, read=dialect, into=into, **opts)
4394
4395
4396def _maybe_copy(instance, copy=True):
4397    return instance.copy() if copy else instance
4398
4399
4400def _is_wrong_expression(expression, into):
4401    return isinstance(expression, Expression) and not isinstance(expression, into)
4402
4403
4404def _apply_builder(
4405    expression,
4406    instance,
4407    arg,
4408    copy=True,
4409    prefix=None,
4410    into=None,
4411    dialect=None,
4412    **opts,
4413):
4414    if _is_wrong_expression(expression, into):
4415        expression = into(this=expression)
4416    instance = _maybe_copy(instance, copy)
4417    expression = maybe_parse(
4418        sql_or_expression=expression,
4419        prefix=prefix,
4420        into=into,
4421        dialect=dialect,
4422        **opts,
4423    )
4424    instance.set(arg, expression)
4425    return instance
4426
4427
4428def _apply_child_list_builder(
4429    *expressions,
4430    instance,
4431    arg,
4432    append=True,
4433    copy=True,
4434    prefix=None,
4435    into=None,
4436    dialect=None,
4437    properties=None,
4438    **opts,
4439):
4440    instance = _maybe_copy(instance, copy)
4441    parsed = []
4442    for expression in expressions:
4443        if _is_wrong_expression(expression, into):
4444            expression = into(expressions=[expression])
4445        expression = maybe_parse(
4446            expression,
4447            into=into,
4448            dialect=dialect,
4449            prefix=prefix,
4450            **opts,
4451        )
4452        parsed.extend(expression.expressions)
4453
4454    existing = instance.args.get(arg)
4455    if append and existing:
4456        parsed = existing.expressions + parsed
4457
4458    child = into(expressions=parsed)
4459    for k, v in (properties or {}).items():
4460        child.set(k, v)
4461    instance.set(arg, child)
4462    return instance
4463
4464
4465def _apply_list_builder(
4466    *expressions,
4467    instance,
4468    arg,
4469    append=True,
4470    copy=True,
4471    prefix=None,
4472    into=None,
4473    dialect=None,
4474    **opts,
4475):
4476    inst = _maybe_copy(instance, copy)
4477
4478    expressions = [
4479        maybe_parse(
4480            sql_or_expression=expression,
4481            into=into,
4482            prefix=prefix,
4483            dialect=dialect,
4484            **opts,
4485        )
4486        for expression in expressions
4487    ]
4488
4489    existing_expressions = inst.args.get(arg)
4490    if append and existing_expressions:
4491        expressions = existing_expressions + expressions
4492
4493    inst.set(arg, expressions)
4494    return inst
4495
4496
4497def _apply_conjunction_builder(
4498    *expressions,
4499    instance,
4500    arg,
4501    into=None,
4502    append=True,
4503    copy=True,
4504    dialect=None,
4505    **opts,
4506):
4507    expressions = [exp for exp in expressions if exp is not None and exp != ""]
4508    if not expressions:
4509        return instance
4510
4511    inst = _maybe_copy(instance, copy)
4512
4513    existing = inst.args.get(arg)
4514    if append and existing is not None:
4515        expressions = [existing.this if into else existing] + list(expressions)
4516
4517    node = and_(*expressions, dialect=dialect, copy=copy, **opts)
4518
4519    inst.set(arg, into(this=node) if into else node)
4520    return inst
4521
4522
4523def _combine(expressions, operator, dialect=None, copy=True, **opts):
4524    expressions = [
4525        condition(expression, dialect=dialect, copy=copy, **opts) for expression in expressions
4526    ]
4527    this = expressions[0]
4528    if expressions[1:]:
4529        this = _wrap(this, Connector)
4530    for expression in expressions[1:]:
4531        this = operator(this=this, expression=_wrap(expression, Connector))
4532    return this
4533
4534
4535def _wrap(expression: E, kind: t.Type[Expression]) -> E | Paren:
4536    if isinstance(expression, kind):
4537        return Paren(this=expression)
4538    return expression
4539
4540
4541def union(left, right, distinct=True, dialect=None, **opts):
4542    """
4543    Initializes a syntax tree from one UNION expression.
4544
4545    Example:
4546        >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
4547        'SELECT * FROM foo UNION SELECT * FROM bla'
4548
4549    Args:
4550        left (str | Expression): the SQL code string corresponding to the left-hand side.
4551            If an `Expression` instance is passed, it will be used as-is.
4552        right (str | Expression): the SQL code string corresponding to the right-hand side.
4553            If an `Expression` instance is passed, it will be used as-is.
4554        distinct (bool): set the DISTINCT flag if and only if this is true.
4555        dialect (str): the dialect used to parse the input expression.
4556        opts (kwargs): other options to use to parse the input expressions.
4557    Returns:
4558        Union: the syntax tree for the UNION expression.
4559    """
4560    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4561    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4562
4563    return Union(this=left, expression=right, distinct=distinct)
4564
4565
4566def intersect(left, right, distinct=True, dialect=None, **opts):
4567    """
4568    Initializes a syntax tree from one INTERSECT expression.
4569
4570    Example:
4571        >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
4572        'SELECT * FROM foo INTERSECT SELECT * FROM bla'
4573
4574    Args:
4575        left (str | Expression): the SQL code string corresponding to the left-hand side.
4576            If an `Expression` instance is passed, it will be used as-is.
4577        right (str | Expression): the SQL code string corresponding to the right-hand side.
4578            If an `Expression` instance is passed, it will be used as-is.
4579        distinct (bool): set the DISTINCT flag if and only if this is true.
4580        dialect (str): the dialect used to parse the input expression.
4581        opts (kwargs): other options to use to parse the input expressions.
4582    Returns:
4583        Intersect: the syntax tree for the INTERSECT expression.
4584    """
4585    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4586    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4587
4588    return Intersect(this=left, expression=right, distinct=distinct)
4589
4590
4591def except_(left, right, distinct=True, dialect=None, **opts):
4592    """
4593    Initializes a syntax tree from one EXCEPT expression.
4594
4595    Example:
4596        >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
4597        'SELECT * FROM foo EXCEPT SELECT * FROM bla'
4598
4599    Args:
4600        left (str | Expression): the SQL code string corresponding to the left-hand side.
4601            If an `Expression` instance is passed, it will be used as-is.
4602        right (str | Expression): the SQL code string corresponding to the right-hand side.
4603            If an `Expression` instance is passed, it will be used as-is.
4604        distinct (bool): set the DISTINCT flag if and only if this is true.
4605        dialect (str): the dialect used to parse the input expression.
4606        opts (kwargs): other options to use to parse the input expressions.
4607    Returns:
4608        Except: the syntax tree for the EXCEPT statement.
4609    """
4610    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4611    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4612
4613    return Except(this=left, expression=right, distinct=distinct)
4614
4615
4616def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
4617    """
4618    Initializes a syntax tree from one or multiple SELECT expressions.
4619
4620    Example:
4621        >>> select("col1", "col2").from_("tbl").sql()
4622        'SELECT col1, col2 FROM tbl'
4623
4624    Args:
4625        *expressions: the SQL code string to parse as the expressions of a
4626            SELECT statement. If an Expression instance is passed, this is used as-is.
4627        dialect: the dialect used to parse the input expressions (in the case that an
4628            input expression is a SQL string).
4629        **opts: other options to use to parse the input expressions (again, in the case
4630            that an input expression is a SQL string).
4631
4632    Returns:
4633        Select: the syntax tree for the SELECT statement.
4634    """
4635    return Select().select(*expressions, dialect=dialect, **opts)
4636
4637
4638def from_(*expressions, dialect=None, **opts) -> Select:
4639    """
4640    Initializes a syntax tree from a FROM expression.
4641
4642    Example:
4643        >>> from_("tbl").select("col1", "col2").sql()
4644        'SELECT col1, col2 FROM tbl'
4645
4646    Args:
4647        *expressions (str | Expression): the SQL code string to parse as the FROM expressions of a
4648            SELECT statement. If an Expression instance is passed, this is used as-is.
4649        dialect (str): the dialect used to parse the input expression (in the case that the
4650            input expression is a SQL string).
4651        **opts: other options to use to parse the input expressions (again, in the case
4652            that the input expression is a SQL string).
4653
4654    Returns:
4655        Select: the syntax tree for the SELECT statement.
4656    """
4657    return Select().from_(*expressions, dialect=dialect, **opts)
4658
4659
4660def update(
4661    table: str | Table,
4662    properties: dict,
4663    where: t.Optional[ExpOrStr] = None,
4664    from_: t.Optional[ExpOrStr] = None,
4665    dialect: DialectType = None,
4666    **opts,
4667) -> Update:
4668    """
4669    Creates an update statement.
4670
4671    Example:
4672        >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
4673        "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
4674
4675    Args:
4676        *properties: dictionary of properties to set which are
4677            auto converted to sql objects eg None -> NULL
4678        where: sql conditional parsed into a WHERE statement
4679        from_: sql statement parsed into a FROM statement
4680        dialect: the dialect used to parse the input expressions.
4681        **opts: other options to use to parse the input expressions.
4682
4683    Returns:
4684        Update: the syntax tree for the UPDATE statement.
4685    """
4686    update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect))
4687    update_expr.set(
4688        "expressions",
4689        [
4690            EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v))
4691            for k, v in properties.items()
4692        ],
4693    )
4694    if from_:
4695        update_expr.set(
4696            "from",
4697            maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts),
4698        )
4699    if isinstance(where, Condition):
4700        where = Where(this=where)
4701    if where:
4702        update_expr.set(
4703            "where",
4704            maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts),
4705        )
4706    return update_expr
4707
4708
4709def delete(
4710    table: ExpOrStr,
4711    where: t.Optional[ExpOrStr] = None,
4712    returning: t.Optional[ExpOrStr] = None,
4713    dialect: DialectType = None,
4714    **opts,
4715) -> Delete:
4716    """
4717    Builds a delete statement.
4718
4719    Example:
4720        >>> delete("my_table", where="id > 1").sql()
4721        'DELETE FROM my_table WHERE id > 1'
4722
4723    Args:
4724        where: sql conditional parsed into a WHERE statement
4725        returning: sql conditional parsed into a RETURNING statement
4726        dialect: the dialect used to parse the input expressions.
4727        **opts: other options to use to parse the input expressions.
4728
4729    Returns:
4730        Delete: the syntax tree for the DELETE statement.
4731    """
4732    delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts)
4733    if where:
4734        delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts)
4735    if returning:
4736        delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts)
4737    return delete_expr
4738
4739
4740def condition(expression, dialect=None, copy=True, **opts) -> Condition:
4741    """
4742    Initialize a logical condition expression.
4743
4744    Example:
4745        >>> condition("x=1").sql()
4746        'x = 1'
4747
4748        This is helpful for composing larger logical syntax trees:
4749        >>> where = condition("x=1")
4750        >>> where = where.and_("y=1")
4751        >>> Select().from_("tbl").select("*").where(where).sql()
4752        'SELECT * FROM tbl WHERE x = 1 AND y = 1'
4753
4754    Args:
4755        *expression (str | Expression): the SQL code string to parse.
4756            If an Expression instance is passed, this is used as-is.
4757        dialect (str): the dialect used to parse the input expression (in the case that the
4758            input expression is a SQL string).
4759        copy (bool): Whether or not to copy `expression` (only applies to expressions).
4760        **opts: other options to use to parse the input expressions (again, in the case
4761            that the input expression is a SQL string).
4762
4763    Returns:
4764        Condition: the expression
4765    """
4766    return maybe_parse(  # type: ignore
4767        expression,
4768        into=Condition,
4769        dialect=dialect,
4770        copy=copy,
4771        **opts,
4772    )
4773
4774
4775def and_(*expressions, dialect=None, copy=True, **opts) -> And:
4776    """
4777    Combine multiple conditions with an AND logical operator.
4778
4779    Example:
4780        >>> and_("x=1", and_("y=1", "z=1")).sql()
4781        'x = 1 AND (y = 1 AND z = 1)'
4782
4783    Args:
4784        *expressions (str | Expression): the SQL code strings to parse.
4785            If an Expression instance is passed, this is used as-is.
4786        dialect (str): the dialect used to parse the input expression.
4787        copy (bool): whether or not to copy `expressions` (only applies to Expressions).
4788        **opts: other options to use to parse the input expressions.
4789
4790    Returns:
4791        And: the new condition
4792    """
4793    return _combine(expressions, And, dialect, copy=copy, **opts)
4794
4795
4796def or_(*expressions, dialect=None, copy=True, **opts) -> Or:
4797    """
4798    Combine multiple conditions with an OR logical operator.
4799
4800    Example:
4801        >>> or_("x=1", or_("y=1", "z=1")).sql()
4802        'x = 1 OR (y = 1 OR z = 1)'
4803
4804    Args:
4805        *expressions (str | Expression): the SQL code strings to parse.
4806            If an Expression instance is passed, this is used as-is.
4807        dialect (str): the dialect used to parse the input expression.
4808        copy (bool): whether or not to copy `expressions` (only applies to Expressions).
4809        **opts: other options to use to parse the input expressions.
4810
4811    Returns:
4812        Or: the new condition
4813    """
4814    return _combine(expressions, Or, dialect, copy=copy, **opts)
4815
4816
4817def not_(expression, dialect=None, copy=True, **opts) -> Not:
4818    """
4819    Wrap a condition with a NOT operator.
4820
4821    Example:
4822        >>> not_("this_suit='black'").sql()
4823        "NOT this_suit = 'black'"
4824
4825    Args:
4826        expression (str | Expression): the SQL code strings to parse.
4827            If an Expression instance is passed, this is used as-is.
4828        dialect (str): the dialect used to parse the input expression.
4829        **opts: other options to use to parse the input expressions.
4830
4831    Returns:
4832        Not: the new condition
4833    """
4834    this = condition(
4835        expression,
4836        dialect=dialect,
4837        copy=copy,
4838        **opts,
4839    )
4840    return Not(this=_wrap(this, Connector))
4841
4842
4843def paren(expression, copy=True) -> Paren:
4844    return Paren(this=_maybe_copy(expression, copy))
4845
4846
4847SAFE_IDENTIFIER_RE = re.compile(r"^[_a-zA-Z][\w]*$")
4848
4849
4850@t.overload
4851def to_identifier(name: None, quoted: t.Optional[bool] = None, copy: bool = True) -> None:
4852    ...
4853
4854
4855@t.overload
4856def to_identifier(
4857    name: str | Identifier, quoted: t.Optional[bool] = None, copy: bool = True
4858) -> Identifier:
4859    ...
4860
4861
4862def to_identifier(name, quoted=None, copy=True):
4863    """Builds an identifier.
4864
4865    Args:
4866        name: The name to turn into an identifier.
4867        quoted: Whether or not force quote the identifier.
4868        copy: Whether or not to copy a passed in Identefier node.
4869
4870    Returns:
4871        The identifier ast node.
4872    """
4873
4874    if name is None:
4875        return None
4876
4877    if isinstance(name, Identifier):
4878        identifier = _maybe_copy(name, copy)
4879    elif isinstance(name, str):
4880        identifier = Identifier(
4881            this=name,
4882            quoted=not SAFE_IDENTIFIER_RE.match(name) if quoted is None else quoted,
4883        )
4884    else:
4885        raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}")
4886    return identifier
4887
4888
4889INTERVAL_STRING_RE = re.compile(r"\s*([0-9]+)\s*([a-zA-Z]+)\s*")
4890
4891
4892def to_interval(interval: str | Literal) -> Interval:
4893    """Builds an interval expression from a string like '1 day' or '5 months'."""
4894    if isinstance(interval, Literal):
4895        if not interval.is_string:
4896            raise ValueError("Invalid interval string.")
4897
4898        interval = interval.this
4899
4900    interval_parts = INTERVAL_STRING_RE.match(interval)  # type: ignore
4901
4902    if not interval_parts:
4903        raise ValueError("Invalid interval string.")
4904
4905    return Interval(
4906        this=Literal.string(interval_parts.group(1)),
4907        unit=Var(this=interval_parts.group(2)),
4908    )
4909
4910
4911@t.overload
4912def to_table(sql_path: str | Table, **kwargs) -> Table:
4913    ...
4914
4915
4916@t.overload
4917def to_table(sql_path: None, **kwargs) -> None:
4918    ...
4919
4920
4921def to_table(sql_path: t.Optional[str | Table], **kwargs) -> t.Optional[Table]:
4922    """
4923    Create a table expression from a `[catalog].[schema].[table]` sql path. Catalog and schema are optional.
4924    If a table is passed in then that table is returned.
4925
4926    Args:
4927        sql_path: a `[catalog].[schema].[table]` string.
4928
4929    Returns:
4930        A table expression.
4931    """
4932    if sql_path is None or isinstance(sql_path, Table):
4933        return sql_path
4934    if not isinstance(sql_path, str):
4935        raise ValueError(f"Invalid type provided for a table: {type(sql_path)}")
4936
4937    catalog, db, table_name = (to_identifier(x) for x in split_num_words(sql_path, ".", 3))
4938    return Table(this=table_name, db=db, catalog=catalog, **kwargs)
4939
4940
4941def to_column(sql_path: str | Column, **kwargs) -> Column:
4942    """
4943    Create a column from a `[table].[column]` sql path. Schema is optional.
4944
4945    If a column is passed in then that column is returned.
4946
4947    Args:
4948        sql_path: `[table].[column]` string
4949    Returns:
4950        Table: A column expression
4951    """
4952    if sql_path is None or isinstance(sql_path, Column):
4953        return sql_path
4954    if not isinstance(sql_path, str):
4955        raise ValueError(f"Invalid type provided for column: {type(sql_path)}")
4956    return column(*reversed(sql_path.split(".")), **kwargs)  # type: ignore
4957
4958
4959def alias_(
4960    expression: ExpOrStr,
4961    alias: str | Identifier,
4962    table: bool | t.Sequence[str | Identifier] = False,
4963    quoted: t.Optional[bool] = None,
4964    dialect: DialectType = None,
4965    **opts,
4966):
4967    """Create an Alias expression.
4968
4969    Example:
4970        >>> alias_('foo', 'bar').sql()
4971        'foo AS bar'
4972
4973        >>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql()
4974        '(SELECT 1, 2) AS bar(a, b)'
4975
4976    Args:
4977        expression: the SQL code strings to parse.
4978            If an Expression instance is passed, this is used as-is.
4979        alias: the alias name to use. If the name has
4980            special characters it is quoted.
4981        table: Whether or not to create a table alias, can also be a list of columns.
4982        quoted: whether or not to quote the alias
4983        dialect: the dialect used to parse the input expression.
4984        **opts: other options to use to parse the input expressions.
4985
4986    Returns:
4987        Alias: the aliased expression
4988    """
4989    exp = maybe_parse(expression, dialect=dialect, **opts)
4990    alias = to_identifier(alias, quoted=quoted)
4991
4992    if table:
4993        table_alias = TableAlias(this=alias)
4994
4995        exp = exp.copy() if isinstance(expression, Expression) else exp
4996        exp.set("alias", table_alias)
4997
4998        if not isinstance(table, bool):
4999            for column in table:
5000                table_alias.append("columns", to_identifier(column, quoted=quoted))
5001
5002        return exp
5003
5004    # We don't set the "alias" arg for Window expressions, because that would add an IDENTIFIER node in
5005    # the AST, representing a "named_window" [1] construct (eg. bigquery). What we want is an ALIAS node
5006    # for the complete Window expression.
5007    #
5008    # [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/window-function-calls
5009
5010    if "alias" in exp.arg_types and not isinstance(exp, Window):
5011        exp = exp.copy()
5012        exp.set("alias", alias)
5013        return exp
5014    return Alias(this=exp, alias=alias)
5015
5016
5017def subquery(expression, alias=None, dialect=None, **opts):
5018    """
5019    Build a subquery expression.
5020
5021    Example:
5022        >>> subquery('select x from tbl', 'bar').select('x').sql()
5023        'SELECT x FROM (SELECT x FROM tbl) AS bar'
5024
5025    Args:
5026        expression (str | Expression): the SQL code strings to parse.
5027            If an Expression instance is passed, this is used as-is.
5028        alias (str | Expression): the alias name to use.
5029        dialect (str): the dialect used to parse the input expression.
5030        **opts: other options to use to parse the input expressions.
5031
5032    Returns:
5033        Select: a new select with the subquery expression included
5034    """
5035
5036    expression = maybe_parse(expression, dialect=dialect, **opts).subquery(alias)
5037    return Select().from_(expression, dialect=dialect, **opts)
5038
5039
5040def column(
5041    col: str | Identifier,
5042    table: t.Optional[str | Identifier] = None,
5043    db: t.Optional[str | Identifier] = None,
5044    catalog: t.Optional[str | Identifier] = None,
5045    quoted: t.Optional[bool] = None,
5046) -> Column:
5047    """
5048    Build a Column.
5049
5050    Args:
5051        col: column name
5052        table: table name
5053        db: db name
5054        catalog: catalog name
5055        quoted: whether or not to force quote each part
5056    Returns:
5057        Column: column instance
5058    """
5059    return Column(
5060        this=to_identifier(col, quoted=quoted),
5061        table=to_identifier(table, quoted=quoted),
5062        db=to_identifier(db, quoted=quoted),
5063        catalog=to_identifier(catalog, quoted=quoted),
5064    )
5065
5066
5067def cast(expression: ExpOrStr, to: str | DataType | DataType.Type, **opts) -> Cast:
5068    """Cast an expression to a data type.
5069
5070    Example:
5071        >>> cast('x + 1', 'int').sql()
5072        'CAST(x + 1 AS INT)'
5073
5074    Args:
5075        expression: The expression to cast.
5076        to: The datatype to cast to.
5077
5078    Returns:
5079        A cast node.
5080    """
5081    expression = maybe_parse(expression, **opts)
5082    return Cast(this=expression, to=DataType.build(to, **opts))
5083
5084
5085def table_(table, db=None, catalog=None, quoted=None, alias=None) -> Table:
5086    """Build a Table.
5087
5088    Args:
5089        table (str | Expression): column name
5090        db (str | Expression): db name
5091        catalog (str | Expression): catalog name
5092
5093    Returns:
5094        Table: table instance
5095    """
5096    return Table(
5097        this=to_identifier(table, quoted=quoted),
5098        db=to_identifier(db, quoted=quoted),
5099        catalog=to_identifier(catalog, quoted=quoted),
5100        alias=TableAlias(this=to_identifier(alias)) if alias else None,
5101    )
5102
5103
5104def values(
5105    values: t.Iterable[t.Tuple[t.Any, ...]],
5106    alias: t.Optional[str] = None,
5107    columns: t.Optional[t.Iterable[str] | t.Dict[str, DataType]] = None,
5108) -> Values:
5109    """Build VALUES statement.
5110
5111    Example:
5112        >>> values([(1, '2')]).sql()
5113        "VALUES (1, '2')"
5114
5115    Args:
5116        values: values statements that will be converted to SQL
5117        alias: optional alias
5118        columns: Optional list of ordered column names or ordered dictionary of column names to types.
5119         If either are provided then an alias is also required.
5120
5121    Returns:
5122        Values: the Values expression object
5123    """
5124    if columns and not alias:
5125        raise ValueError("Alias is required when providing columns")
5126
5127    return Values(
5128        expressions=[convert(tup) for tup in values],
5129        alias=(
5130            TableAlias(this=to_identifier(alias), columns=[to_identifier(x) for x in columns])
5131            if columns
5132            else (TableAlias(this=to_identifier(alias)) if alias else None)
5133        ),
5134    )
5135
5136
5137def var(name: t.Optional[ExpOrStr]) -> Var:
5138    """Build a SQL variable.
5139
5140    Example:
5141        >>> repr(var('x'))
5142        '(VAR this: x)'
5143
5144        >>> repr(var(column('x', table='y')))
5145        '(VAR this: x)'
5146
5147    Args:
5148        name: The name of the var or an expression who's name will become the var.
5149
5150    Returns:
5151        The new variable node.
5152    """
5153    if not name:
5154        raise ValueError("Cannot convert empty name into var.")
5155
5156    if isinstance(name, Expression):
5157        name = name.name
5158    return Var(this=name)
5159
5160
5161def rename_table(old_name: str | Table, new_name: str | Table) -> AlterTable:
5162    """Build ALTER TABLE... RENAME... expression
5163
5164    Args:
5165        old_name: The old name of the table
5166        new_name: The new name of the table
5167
5168    Returns:
5169        Alter table expression
5170    """
5171    old_table = to_table(old_name)
5172    new_table = to_table(new_name)
5173    return AlterTable(
5174        this=old_table,
5175        actions=[
5176            RenameTable(this=new_table),
5177        ],
5178    )
5179
5180
5181def convert(value: t.Any, copy: bool = False) -> Expression:
5182    """Convert a python value into an expression object.
5183
5184    Raises an error if a conversion is not possible.
5185
5186    Args:
5187        value: A python object.
5188        copy: Whether or not to copy `value` (only applies to Expressions and collections).
5189
5190    Returns:
5191        Expression: the equivalent expression object.
5192    """
5193    if isinstance(value, Expression):
5194        return _maybe_copy(value, copy)
5195    if isinstance(value, str):
5196        return Literal.string(value)
5197    if isinstance(value, bool):
5198        return Boolean(this=value)
5199    if value is None or (isinstance(value, float) and math.isnan(value)):
5200        return NULL
5201    if isinstance(value, numbers.Number):
5202        return Literal.number(value)
5203    if isinstance(value, datetime.datetime):
5204        datetime_literal = Literal.string(
5205            (value if value.tzinfo else value.replace(tzinfo=datetime.timezone.utc)).isoformat()
5206        )
5207        return TimeStrToTime(this=datetime_literal)
5208    if isinstance(value, datetime.date):
5209        date_literal = Literal.string(value.strftime("%Y-%m-%d"))
5210        return DateStrToDate(this=date_literal)
5211    if isinstance(value, tuple):
5212        return Tuple(expressions=[convert(v, copy=copy) for v in value])
5213    if isinstance(value, list):
5214        return Array(expressions=[convert(v, copy=copy) for v in value])
5215    if isinstance(value, dict):
5216        return Map(
5217            keys=[convert(k, copy=copy) for k in value],
5218            values=[convert(v, copy=copy) for v in value.values()],
5219        )
5220    raise ValueError(f"Cannot convert {value}")
5221
5222
5223def replace_children(expression, fun, *args, **kwargs):
5224    """
5225    Replace children of an expression with the result of a lambda fun(child) -> exp.
5226    """
5227    for k, v in expression.args.items():
5228        is_list_arg = type(v) is list
5229
5230        child_nodes = v if is_list_arg else [v]
5231        new_child_nodes = []
5232
5233        for cn in child_nodes:
5234            if isinstance(cn, Expression):
5235                for child_node in ensure_collection(fun(cn, *args, **kwargs)):
5236                    new_child_nodes.append(child_node)
5237                    child_node.parent = expression
5238                    child_node.arg_key = k
5239            else:
5240                new_child_nodes.append(cn)
5241
5242        expression.args[k] = new_child_nodes if is_list_arg else seq_get(new_child_nodes, 0)
5243
5244
5245def column_table_names(expression):
5246    """
5247    Return all table names referenced through columns in an expression.
5248
5249    Example:
5250        >>> import sqlglot
5251        >>> column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e"))
5252        ['c', 'a']
5253
5254    Args:
5255        expression (sqlglot.Expression): expression to find table names
5256
5257    Returns:
5258        list: A list of unique names
5259    """
5260    return list(dict.fromkeys(column.table for column in expression.find_all(Column)))
5261
5262
5263def table_name(table) -> str:
5264    """Get the full name of a table as a string.
5265
5266    Args:
5267        table (exp.Table | str): table expression node or string.
5268
5269    Examples:
5270        >>> from sqlglot import exp, parse_one
5271        >>> table_name(parse_one("select * from a.b.c").find(exp.Table))
5272        'a.b.c'
5273
5274    Returns:
5275        The table name.
5276    """
5277
5278    table = maybe_parse(table, into=Table)
5279
5280    if not table:
5281        raise ValueError(f"Cannot parse {table}")
5282
5283    return ".".join(
5284        part
5285        for part in (
5286            table.text("catalog"),
5287            table.text("db"),
5288            table.name,
5289        )
5290        if part
5291    )
5292
5293
5294def replace_tables(expression, mapping):
5295    """Replace all tables in expression according to the mapping.
5296
5297    Args:
5298        expression (sqlglot.Expression): expression node to be transformed and replaced.
5299        mapping (Dict[str, str]): mapping of table names.
5300
5301    Examples:
5302        >>> from sqlglot import exp, parse_one
5303        >>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql()
5304        'SELECT * FROM c'
5305
5306    Returns:
5307        The mapped expression.
5308    """
5309
5310    def _replace_tables(node):
5311        if isinstance(node, Table):
5312            new_name = mapping.get(table_name(node))
5313            if new_name:
5314                return to_table(
5315                    new_name,
5316                    **{k: v for k, v in node.args.items() if k not in ("this", "db", "catalog")},
5317                )
5318        return node
5319
5320    return expression.transform(_replace_tables)
5321
5322
5323def replace_placeholders(expression, *args, **kwargs):
5324    """Replace placeholders in an expression.
5325
5326    Args:
5327        expression (sqlglot.Expression): expression node to be transformed and replaced.
5328        args: positional names that will substitute unnamed placeholders in the given order.
5329        kwargs: keyword arguments that will substitute named placeholders.
5330
5331    Examples:
5332        >>> from sqlglot import exp, parse_one
5333        >>> replace_placeholders(
5334        ...     parse_one("select * from :tbl where ? = ?"),
5335        ...     exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo")
5336        ... ).sql()
5337        "SELECT * FROM foo WHERE str_col = 'b'"
5338
5339    Returns:
5340        The mapped expression.
5341    """
5342
5343    def _replace_placeholders(node, args, **kwargs):
5344        if isinstance(node, Placeholder):
5345            if node.name:
5346                new_name = kwargs.get(node.name)
5347                if new_name:
5348                    return convert(new_name)
5349            else:
5350                try:
5351                    return convert(next(args))
5352                except StopIteration:
5353                    pass
5354        return node
5355
5356    return expression.transform(_replace_placeholders, iter(args), **kwargs)
5357
5358
5359def expand(
5360    expression: Expression, sources: t.Dict[str, Subqueryable], copy: bool = True
5361) -> Expression:
5362    """Transforms an expression by expanding all referenced sources into subqueries.
5363
5364    Examples:
5365        >>> from sqlglot import parse_one
5366        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql()
5367        'SELECT * FROM (SELECT * FROM y) AS z /* source: x */'
5368
5369        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y"), "y": parse_one("select * from z")}).sql()
5370        'SELECT * FROM (SELECT * FROM (SELECT * FROM z) AS y /* source: y */) AS z /* source: x */'
5371
5372    Args:
5373        expression: The expression to expand.
5374        sources: A dictionary of name to Subqueryables.
5375        copy: Whether or not to copy the expression during transformation. Defaults to True.
5376
5377    Returns:
5378        The transformed expression.
5379    """
5380
5381    def _expand(node: Expression):
5382        if isinstance(node, Table):
5383            name = table_name(node)
5384            source = sources.get(name)
5385            if source:
5386                subquery = source.subquery(node.alias or name)
5387                subquery.comments = [f"source: {name}"]
5388                return subquery.transform(_expand, copy=False)
5389        return node
5390
5391    return expression.transform(_expand, copy=copy)
5392
5393
5394def func(name: str, *args, dialect: DialectType = None, **kwargs) -> Func:
5395    """
5396    Returns a Func expression.
5397
5398    Examples:
5399        >>> func("abs", 5).sql()
5400        'ABS(5)'
5401
5402        >>> func("cast", this=5, to=DataType.build("DOUBLE")).sql()
5403        'CAST(5 AS DOUBLE)'
5404
5405    Args:
5406        name: the name of the function to build.
5407        args: the args used to instantiate the function of interest.
5408        dialect: the source dialect.
5409        kwargs: the kwargs used to instantiate the function of interest.
5410
5411    Note:
5412        The arguments `args` and `kwargs` are mutually exclusive.
5413
5414    Returns:
5415        An instance of the function of interest, or an anonymous function, if `name` doesn't
5416        correspond to an existing `sqlglot.expressions.Func` class.
5417    """
5418    if args and kwargs:
5419        raise ValueError("Can't use both args and kwargs to instantiate a function.")
5420
5421    from sqlglot.dialects.dialect import Dialect
5422
5423    converted: t.List[Expression] = [maybe_parse(arg, dialect=dialect) for arg in args]
5424    kwargs = {key: maybe_parse(value, dialect=dialect) for key, value in kwargs.items()}
5425
5426    parser = Dialect.get_or_raise(dialect)().parser()
5427    from_args_list = parser.FUNCTIONS.get(name.upper())
5428
5429    if from_args_list:
5430        function = from_args_list(converted) if converted else from_args_list.__self__(**kwargs)  # type: ignore
5431    else:
5432        kwargs = kwargs or {"expressions": converted}
5433        function = Anonymous(this=name, **kwargs)
5434
5435    for error_message in function.error_messages(converted):
5436        raise ValueError(error_message)
5437
5438    return function
5439
5440
5441def true():
5442    """
5443    Returns a true Boolean expression.
5444    """
5445    return Boolean(this=True)
5446
5447
5448def false():
5449    """
5450    Returns a false Boolean expression.
5451    """
5452    return Boolean(this=False)
5453
5454
5455def null():
5456    """
5457    Returns a Null expression.
5458    """
5459    return Null()
5460
5461
5462# TODO: deprecate this
5463TRUE = Boolean(this=True)
5464FALSE = Boolean(this=False)
5465NULL = Null()
class Expression:
 57class Expression(metaclass=_Expression):
 58    """
 59    The base class for all expressions in a syntax tree. Each Expression encapsulates any necessary
 60    context, such as its child expressions, their names (arg keys), and whether a given child expression
 61    is optional or not.
 62
 63    Attributes:
 64        key: a unique key for each class in the Expression hierarchy. This is useful for hashing
 65            and representing expressions as strings.
 66        arg_types: determines what arguments (child nodes) are supported by an expression. It
 67            maps arg keys to booleans that indicate whether the corresponding args are optional.
 68        parent: a reference to the parent expression (or None, in case of root expressions).
 69        arg_key: the arg key an expression is associated with, i.e. the name its parent expression
 70            uses to refer to it.
 71        comments: a list of comments that are associated with a given expression. This is used in
 72            order to preserve comments when transpiling SQL code.
 73        _type: the `sqlglot.expressions.DataType` type of an expression. This is inferred by the
 74            optimizer, in order to enable some transformations that require type information.
 75
 76    Example:
 77        >>> class Foo(Expression):
 78        ...     arg_types = {"this": True, "expression": False}
 79
 80        The above definition informs us that Foo is an Expression that requires an argument called
 81        "this" and may also optionally receive an argument called "expression".
 82
 83    Args:
 84        args: a mapping used for retrieving the arguments of an expression, given their arg keys.
 85    """
 86
 87    key = "expression"
 88    arg_types = {"this": True}
 89    __slots__ = ("args", "parent", "arg_key", "comments", "_type", "_meta", "_hash")
 90
 91    def __init__(self, **args: t.Any):
 92        self.args: t.Dict[str, t.Any] = args
 93        self.parent: t.Optional[Expression] = None
 94        self.arg_key: t.Optional[str] = None
 95        self.comments: t.Optional[t.List[str]] = None
 96        self._type: t.Optional[DataType] = None
 97        self._meta: t.Optional[t.Dict[str, t.Any]] = None
 98        self._hash: t.Optional[int] = None
 99
100        for arg_key, value in self.args.items():
101            self._set_parent(arg_key, value)
102
103    def __eq__(self, other) -> bool:
104        return type(self) is type(other) and hash(self) == hash(other)
105
106    @property
107    def hashable_args(self) -> t.Any:
108        args = (self.args.get(k) for k in self.arg_types)
109
110        return tuple(
111            (tuple(_norm_arg(a) for a in arg) if arg else None)
112            if type(arg) is list
113            else (_norm_arg(arg) if arg is not None and arg is not False else None)
114            for arg in args
115        )
116
117    def __hash__(self) -> int:
118        if self._hash is not None:
119            return self._hash
120
121        return hash((self.__class__, self.hashable_args))
122
123    @property
124    def this(self):
125        """
126        Retrieves the argument with key "this".
127        """
128        return self.args.get("this")
129
130    @property
131    def expression(self):
132        """
133        Retrieves the argument with key "expression".
134        """
135        return self.args.get("expression")
136
137    @property
138    def expressions(self):
139        """
140        Retrieves the argument with key "expressions".
141        """
142        return self.args.get("expressions") or []
143
144    def text(self, key) -> str:
145        """
146        Returns a textual representation of the argument corresponding to "key". This can only be used
147        for args that are strings or leaf Expression instances, such as identifiers and literals.
148        """
149        field = self.args.get(key)
150        if isinstance(field, str):
151            return field
152        if isinstance(field, (Identifier, Literal, Var)):
153            return field.this
154        if isinstance(field, (Star, Null)):
155            return field.name
156        return ""
157
158    @property
159    def is_string(self) -> bool:
160        """
161        Checks whether a Literal expression is a string.
162        """
163        return isinstance(self, Literal) and self.args["is_string"]
164
165    @property
166    def is_number(self) -> bool:
167        """
168        Checks whether a Literal expression is a number.
169        """
170        return isinstance(self, Literal) and not self.args["is_string"]
171
172    @property
173    def is_int(self) -> bool:
174        """
175        Checks whether a Literal expression is an integer.
176        """
177        if self.is_number:
178            try:
179                int(self.name)
180                return True
181            except ValueError:
182                pass
183        return False
184
185    @property
186    def is_star(self) -> bool:
187        """Checks whether an expression is a star."""
188        return isinstance(self, Star) or (isinstance(self, Column) and isinstance(self.this, Star))
189
190    @property
191    def alias(self) -> str:
192        """
193        Returns the alias of the expression, or an empty string if it's not aliased.
194        """
195        if isinstance(self.args.get("alias"), TableAlias):
196            return self.args["alias"].name
197        return self.text("alias")
198
199    @property
200    def name(self) -> str:
201        return self.text("this")
202
203    @property
204    def alias_or_name(self):
205        return self.alias or self.name
206
207    @property
208    def output_name(self):
209        """
210        Name of the output column if this expression is a selection.
211
212        If the Expression has no output name, an empty string is returned.
213
214        Example:
215            >>> from sqlglot import parse_one
216            >>> parse_one("SELECT a").expressions[0].output_name
217            'a'
218            >>> parse_one("SELECT b AS c").expressions[0].output_name
219            'c'
220            >>> parse_one("SELECT 1 + 2").expressions[0].output_name
221            ''
222        """
223        return ""
224
225    @property
226    def type(self) -> t.Optional[DataType]:
227        return self._type
228
229    @type.setter
230    def type(self, dtype: t.Optional[DataType | DataType.Type | str]) -> None:
231        if dtype and not isinstance(dtype, DataType):
232            dtype = DataType.build(dtype)
233        self._type = dtype  # type: ignore
234
235    @property
236    def meta(self) -> t.Dict[str, t.Any]:
237        if self._meta is None:
238            self._meta = {}
239        return self._meta
240
241    def __deepcopy__(self, memo):
242        copy = self.__class__(**deepcopy(self.args))
243        if self.comments is not None:
244            copy.comments = deepcopy(self.comments)
245
246        if self._type is not None:
247            copy._type = self._type.copy()
248
249        if self._meta is not None:
250            copy._meta = deepcopy(self._meta)
251
252        return copy
253
254    def copy(self):
255        """
256        Returns a deep copy of the expression.
257        """
258        new = deepcopy(self)
259        new.parent = self.parent
260        return new
261
262    def add_comments(self, comments: t.Optional[t.List[str]]) -> None:
263        if self.comments is None:
264            self.comments = []
265        if comments:
266            self.comments.extend(comments)
267
268    def append(self, arg_key, value):
269        """
270        Appends value to arg_key if it's a list or sets it as a new list.
271
272        Args:
273            arg_key (str): name of the list expression arg
274            value (Any): value to append to the list
275        """
276        if not isinstance(self.args.get(arg_key), list):
277            self.args[arg_key] = []
278        self.args[arg_key].append(value)
279        self._set_parent(arg_key, value)
280
281    def set(self, arg_key, value):
282        """
283        Sets `arg_key` to `value`.
284
285        Args:
286            arg_key (str): name of the expression arg.
287            value: value to set the arg to.
288        """
289        self.args[arg_key] = value
290        self._set_parent(arg_key, value)
291
292    def _set_parent(self, arg_key, value):
293        if hasattr(value, "parent"):
294            value.parent = self
295            value.arg_key = arg_key
296        elif type(value) is list:
297            for v in value:
298                if hasattr(v, "parent"):
299                    v.parent = self
300                    v.arg_key = arg_key
301
302    @property
303    def depth(self):
304        """
305        Returns the depth of this tree.
306        """
307        if self.parent:
308            return self.parent.depth + 1
309        return 0
310
311    def iter_expressions(self) -> t.Iterator[t.Tuple[str, Expression]]:
312        """Yields the key and expression for all arguments, exploding list args."""
313        for k, vs in self.args.items():
314            if type(vs) is list:
315                for v in vs:
316                    if hasattr(v, "parent"):
317                        yield k, v
318            else:
319                if hasattr(vs, "parent"):
320                    yield k, vs
321
322    def find(self, *expression_types: t.Type[E], bfs=True) -> E | None:
323        """
324        Returns the first node in this tree which matches at least one of
325        the specified types.
326
327        Args:
328            expression_types: the expression type(s) to match.
329
330        Returns:
331            The node which matches the criteria or None if no such node was found.
332        """
333        return next(self.find_all(*expression_types, bfs=bfs), None)
334
335    def find_all(self, *expression_types: t.Type[E], bfs=True) -> t.Iterator[E]:
336        """
337        Returns a generator object which visits all nodes in this tree and only
338        yields those that match at least one of the specified expression types.
339
340        Args:
341            expression_types: the expression type(s) to match.
342
343        Returns:
344            The generator object.
345        """
346        for expression, *_ in self.walk(bfs=bfs):
347            if isinstance(expression, expression_types):
348                yield expression
349
350    def find_ancestor(self, *expression_types: t.Type[E]) -> E | None:
351        """
352        Returns a nearest parent matching expression_types.
353
354        Args:
355            expression_types: the expression type(s) to match.
356
357        Returns:
358            The parent node.
359        """
360        ancestor = self.parent
361        while ancestor and not isinstance(ancestor, expression_types):
362            ancestor = ancestor.parent
363        return t.cast(E, ancestor)
364
365    @property
366    def parent_select(self):
367        """
368        Returns the parent select statement.
369        """
370        return self.find_ancestor(Select)
371
372    @property
373    def same_parent(self):
374        """Returns if the parent is the same class as itself."""
375        return type(self.parent) is self.__class__
376
377    def root(self) -> Expression:
378        """
379        Returns the root expression of this tree.
380        """
381        expression = self
382        while expression.parent:
383            expression = expression.parent
384        return expression
385
386    def walk(self, bfs=True, prune=None):
387        """
388        Returns a generator object which visits all nodes in this tree.
389
390        Args:
391            bfs (bool): if set to True the BFS traversal order will be applied,
392                otherwise the DFS traversal will be used instead.
393            prune ((node, parent, arg_key) -> bool): callable that returns True if
394                the generator should stop traversing this branch of the tree.
395
396        Returns:
397            the generator object.
398        """
399        if bfs:
400            yield from self.bfs(prune=prune)
401        else:
402            yield from self.dfs(prune=prune)
403
404    def dfs(self, parent=None, key=None, prune=None):
405        """
406        Returns a generator object which visits all nodes in this tree in
407        the DFS (Depth-first) order.
408
409        Returns:
410            The generator object.
411        """
412        parent = parent or self.parent
413        yield self, parent, key
414        if prune and prune(self, parent, key):
415            return
416
417        for k, v in self.iter_expressions():
418            yield from v.dfs(self, k, prune)
419
420    def bfs(self, prune=None):
421        """
422        Returns a generator object which visits all nodes in this tree in
423        the BFS (Breadth-first) order.
424
425        Returns:
426            The generator object.
427        """
428        queue = deque([(self, self.parent, None)])
429
430        while queue:
431            item, parent, key = queue.popleft()
432
433            yield item, parent, key
434            if prune and prune(item, parent, key):
435                continue
436
437            for k, v in item.iter_expressions():
438                queue.append((v, item, k))
439
440    def unnest(self):
441        """
442        Returns the first non parenthesis child or self.
443        """
444        expression = self
445        while type(expression) is Paren:
446            expression = expression.this
447        return expression
448
449    def unalias(self):
450        """
451        Returns the inner expression if this is an Alias.
452        """
453        if isinstance(self, Alias):
454            return self.this
455        return self
456
457    def unnest_operands(self):
458        """
459        Returns unnested operands as a tuple.
460        """
461        return tuple(arg.unnest() for _, arg in self.iter_expressions())
462
463    def flatten(self, unnest=True):
464        """
465        Returns a generator which yields child nodes who's parents are the same class.
466
467        A AND B AND C -> [A, B, C]
468        """
469        for node, _, _ in self.dfs(prune=lambda n, p, *_: p and not type(n) is self.__class__):
470            if not type(node) is self.__class__:
471                yield node.unnest() if unnest else node
472
473    def __str__(self):
474        return self.sql()
475
476    def __repr__(self):
477        return self._to_s()
478
479    def sql(self, dialect: DialectType = None, **opts) -> str:
480        """
481        Returns SQL string representation of this tree.
482
483        Args:
484            dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
485            opts: other `sqlglot.generator.Generator` options.
486
487        Returns:
488            The SQL string.
489        """
490        from sqlglot.dialects import Dialect
491
492        return Dialect.get_or_raise(dialect)().generate(self, **opts)
493
494    def _to_s(self, hide_missing: bool = True, level: int = 0) -> str:
495        indent = "" if not level else "\n"
496        indent += "".join(["  "] * level)
497        left = f"({self.key.upper()} "
498
499        args: t.Dict[str, t.Any] = {
500            k: ", ".join(
501                v._to_s(hide_missing=hide_missing, level=level + 1)
502                if hasattr(v, "_to_s")
503                else str(v)
504                for v in ensure_list(vs)
505                if v is not None
506            )
507            for k, vs in self.args.items()
508        }
509        args["comments"] = self.comments
510        args["type"] = self.type
511        args = {k: v for k, v in args.items() if v or not hide_missing}
512
513        right = ", ".join(f"{k}: {v}" for k, v in args.items())
514        right += ")"
515
516        return indent + left + right
517
518    def transform(self, fun, *args, copy=True, **kwargs):
519        """
520        Recursively visits all tree nodes (excluding already transformed ones)
521        and applies the given transformation function to each node.
522
523        Args:
524            fun (function): a function which takes a node as an argument and returns a
525                new transformed node or the same node without modifications. If the function
526                returns None, then the corresponding node will be removed from the syntax tree.
527            copy (bool): if set to True a new tree instance is constructed, otherwise the tree is
528                modified in place.
529
530        Returns:
531            The transformed tree.
532        """
533        node = self.copy() if copy else self
534        new_node = fun(node, *args, **kwargs)
535
536        if new_node is None or not isinstance(new_node, Expression):
537            return new_node
538        if new_node is not node:
539            new_node.parent = node.parent
540            return new_node
541
542        replace_children(new_node, lambda child: child.transform(fun, *args, copy=False, **kwargs))
543        return new_node
544
545    def replace(self, expression):
546        """
547        Swap out this expression with a new expression.
548
549        For example::
550
551            >>> tree = Select().select("x").from_("tbl")
552            >>> tree.find(Column).replace(Column(this="y"))
553            (COLUMN this: y)
554            >>> tree.sql()
555            'SELECT y FROM tbl'
556
557        Args:
558            expression (Expression|None): new node
559
560        Returns:
561            The new expression or expressions.
562        """
563        if not self.parent:
564            return expression
565
566        parent = self.parent
567        self.parent = None
568
569        replace_children(parent, lambda child: expression if child is self else child)
570        return expression
571
572    def pop(self):
573        """
574        Remove this expression from its AST.
575
576        Returns:
577            The popped expression.
578        """
579        self.replace(None)
580        return self
581
582    def assert_is(self, type_):
583        """
584        Assert that this `Expression` is an instance of `type_`.
585
586        If it is NOT an instance of `type_`, this raises an assertion error.
587        Otherwise, this returns this expression.
588
589        Examples:
590            This is useful for type security in chained expressions:
591
592            >>> import sqlglot
593            >>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql()
594            'SELECT x, z FROM y'
595        """
596        assert isinstance(self, type_)
597        return self
598
599    def error_messages(self, args: t.Optional[t.Sequence] = None) -> t.List[str]:
600        """
601        Checks if this expression is valid (e.g. all mandatory args are set).
602
603        Args:
604            args: a sequence of values that were used to instantiate a Func expression. This is used
605                to check that the provided arguments don't exceed the function argument limit.
606
607        Returns:
608            A list of error messages for all possible errors that were found.
609        """
610        errors: t.List[str] = []
611
612        for k in self.args:
613            if k not in self.arg_types:
614                errors.append(f"Unexpected keyword: '{k}' for {self.__class__}")
615        for k, mandatory in self.arg_types.items():
616            v = self.args.get(k)
617            if mandatory and (v is None or (isinstance(v, list) and not v)):
618                errors.append(f"Required keyword: '{k}' missing for {self.__class__}")
619
620        if (
621            args
622            and isinstance(self, Func)
623            and len(args) > len(self.arg_types)
624            and not self.is_var_len_args
625        ):
626            errors.append(
627                f"The number of provided arguments ({len(args)}) is greater than "
628                f"the maximum number of supported arguments ({len(self.arg_types)})"
629            )
630
631        return errors
632
633    def dump(self):
634        """
635        Dump this Expression to a JSON-serializable dict.
636        """
637        from sqlglot.serde import dump
638
639        return dump(self)
640
641    @classmethod
642    def load(cls, obj):
643        """
644        Load a dict (as returned by `Expression.dump`) into an Expression instance.
645        """
646        from sqlglot.serde import load
647
648        return load(obj)

The base class for all expressions in a syntax tree. Each Expression encapsulates any necessary context, such as its child expressions, their names (arg keys), and whether a given child expression is optional or not.

Attributes:
  • key: a unique key for each class in the Expression hierarchy. This is useful for hashing and representing expressions as strings.
  • arg_types: determines what arguments (child nodes) are supported by an expression. It maps arg keys to booleans that indicate whether the corresponding args are optional.
  • parent: a reference to the parent expression (or None, in case of root expressions).
  • arg_key: the arg key an expression is associated with, i.e. the name its parent expression uses to refer to it.
  • comments: a list of comments that are associated with a given expression. This is used in order to preserve comments when transpiling SQL code.
  • _type: the sqlglot.expressions.DataType type of an expression. This is inferred by the optimizer, in order to enable some transformations that require type information.
Example:
>>> class Foo(Expression):
...     arg_types = {"this": True, "expression": False}

The above definition informs us that Foo is an Expression that requires an argument called "this" and may also optionally receive an argument called "expression".

Arguments:
  • args: a mapping used for retrieving the arguments of an expression, given their arg keys.
Expression(**args: Any)
 91    def __init__(self, **args: t.Any):
 92        self.args: t.Dict[str, t.Any] = args
 93        self.parent: t.Optional[Expression] = None
 94        self.arg_key: t.Optional[str] = None
 95        self.comments: t.Optional[t.List[str]] = None
 96        self._type: t.Optional[DataType] = None
 97        self._meta: t.Optional[t.Dict[str, t.Any]] = None
 98        self._hash: t.Optional[int] = None
 99
100        for arg_key, value in self.args.items():
101            self._set_parent(arg_key, value)
this

Retrieves the argument with key "this".

expression

Retrieves the argument with key "expression".

expressions

Retrieves the argument with key "expressions".

def text(self, key) -> str:
144    def text(self, key) -> str:
145        """
146        Returns a textual representation of the argument corresponding to "key". This can only be used
147        for args that are strings or leaf Expression instances, such as identifiers and literals.
148        """
149        field = self.args.get(key)
150        if isinstance(field, str):
151            return field
152        if isinstance(field, (Identifier, Literal, Var)):
153            return field.this
154        if isinstance(field, (Star, Null)):
155            return field.name
156        return ""

Returns a textual representation of the argument corresponding to "key". This can only be used for args that are strings or leaf Expression instances, such as identifiers and literals.

is_string: bool

Checks whether a Literal expression is a string.

is_number: bool

Checks whether a Literal expression is a number.

is_int: bool

Checks whether a Literal expression is an integer.

is_star: bool

Checks whether an expression is a star.

alias: str

Returns the alias of the expression, or an empty string if it's not aliased.

output_name

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
def copy(self):
254    def copy(self):
255        """
256        Returns a deep copy of the expression.
257        """
258        new = deepcopy(self)
259        new.parent = self.parent
260        return new

Returns a deep copy of the expression.

def add_comments(self, comments: Optional[List[str]]) -> None:
262    def add_comments(self, comments: t.Optional[t.List[str]]) -> None:
263        if self.comments is None:
264            self.comments = []
265        if comments:
266            self.comments.extend(comments)
def append(self, arg_key, value):
268    def append(self, arg_key, value):
269        """
270        Appends value to arg_key if it's a list or sets it as a new list.
271
272        Args:
273            arg_key (str): name of the list expression arg
274            value (Any): value to append to the list
275        """
276        if not isinstance(self.args.get(arg_key), list):
277            self.args[arg_key] = []
278        self.args[arg_key].append(value)
279        self._set_parent(arg_key, value)

Appends value to arg_key if it's a list or sets it as a new list.

Arguments:
  • arg_key (str): name of the list expression arg
  • value (Any): value to append to the list
def set(self, arg_key, value):
281    def set(self, arg_key, value):
282        """
283        Sets `arg_key` to `value`.
284
285        Args:
286            arg_key (str): name of the expression arg.
287            value: value to set the arg to.
288        """
289        self.args[arg_key] = value
290        self._set_parent(arg_key, value)

Sets arg_key to value.

Arguments:
  • arg_key (str): name of the expression arg.
  • value: value to set the arg to.
depth

Returns the depth of this tree.

def iter_expressions(self) -> Iterator[Tuple[str, sqlglot.expressions.Expression]]:
311    def iter_expressions(self) -> t.Iterator[t.Tuple[str, Expression]]:
312        """Yields the key and expression for all arguments, exploding list args."""
313        for k, vs in self.args.items():
314            if type(vs) is list:
315                for v in vs:
316                    if hasattr(v, "parent"):
317                        yield k, v
318            else:
319                if hasattr(vs, "parent"):
320                    yield k, vs

Yields the key and expression for all arguments, exploding list args.

def find(self, *expression_types: Type[~E], bfs=True) -> Optional[~E]:
322    def find(self, *expression_types: t.Type[E], bfs=True) -> E | None:
323        """
324        Returns the first node in this tree which matches at least one of
325        the specified types.
326
327        Args:
328            expression_types: the expression type(s) to match.
329
330        Returns:
331            The node which matches the criteria or None if no such node was found.
332        """
333        return next(self.find_all(*expression_types, bfs=bfs), None)

Returns the first node in this tree which matches at least one of the specified types.

Arguments:
  • expression_types: the expression type(s) to match.
Returns:

The node which matches the criteria or None if no such node was found.

def find_all(self, *expression_types: Type[~E], bfs=True) -> Iterator[~E]:
335    def find_all(self, *expression_types: t.Type[E], bfs=True) -> t.Iterator[E]:
336        """
337        Returns a generator object which visits all nodes in this tree and only
338        yields those that match at least one of the specified expression types.
339
340        Args:
341            expression_types: the expression type(s) to match.
342
343        Returns:
344            The generator object.
345        """
346        for expression, *_ in self.walk(bfs=bfs):
347            if isinstance(expression, expression_types):
348                yield expression

Returns a generator object which visits all nodes in this tree and only yields those that match at least one of the specified expression types.

Arguments:
  • expression_types: the expression type(s) to match.
Returns:

The generator object.

def find_ancestor(self, *expression_types: Type[~E]) -> Optional[~E]:
350    def find_ancestor(self, *expression_types: t.Type[E]) -> E | None:
351        """
352        Returns a nearest parent matching expression_types.
353
354        Args:
355            expression_types: the expression type(s) to match.
356
357        Returns:
358            The parent node.
359        """
360        ancestor = self.parent
361        while ancestor and not isinstance(ancestor, expression_types):
362            ancestor = ancestor.parent
363        return t.cast(E, ancestor)

Returns a nearest parent matching expression_types.

Arguments:
  • expression_types: the expression type(s) to match.
Returns:

The parent node.

parent_select

Returns the parent select statement.

same_parent

Returns if the parent is the same class as itself.

def root(self) -> sqlglot.expressions.Expression:
377    def root(self) -> Expression:
378        """
379        Returns the root expression of this tree.
380        """
381        expression = self
382        while expression.parent:
383            expression = expression.parent
384        return expression

Returns the root expression of this tree.

def walk(self, bfs=True, prune=None):
386    def walk(self, bfs=True, prune=None):
387        """
388        Returns a generator object which visits all nodes in this tree.
389
390        Args:
391            bfs (bool): if set to True the BFS traversal order will be applied,
392                otherwise the DFS traversal will be used instead.
393            prune ((node, parent, arg_key) -> bool): callable that returns True if
394                the generator should stop traversing this branch of the tree.
395
396        Returns:
397            the generator object.
398        """
399        if bfs:
400            yield from self.bfs(prune=prune)
401        else:
402            yield from self.dfs(prune=prune)

Returns a generator object which visits all nodes in this tree.

Arguments:
  • bfs (bool): if set to True the BFS traversal order will be applied, otherwise the DFS traversal will be used instead.
  • prune ((node, parent, arg_key) -> bool): callable that returns True if the generator should stop traversing this branch of the tree.
Returns:

the generator object.

def dfs(self, parent=None, key=None, prune=None):
404    def dfs(self, parent=None, key=None, prune=None):
405        """
406        Returns a generator object which visits all nodes in this tree in
407        the DFS (Depth-first) order.
408
409        Returns:
410            The generator object.
411        """
412        parent = parent or self.parent
413        yield self, parent, key
414        if prune and prune(self, parent, key):
415            return
416
417        for k, v in self.iter_expressions():
418            yield from v.dfs(self, k, prune)

Returns a generator object which visits all nodes in this tree in the DFS (Depth-first) order.

Returns:

The generator object.

def bfs(self, prune=None):
420    def bfs(self, prune=None):
421        """
422        Returns a generator object which visits all nodes in this tree in
423        the BFS (Breadth-first) order.
424
425        Returns:
426            The generator object.
427        """
428        queue = deque([(self, self.parent, None)])
429
430        while queue:
431            item, parent, key = queue.popleft()
432
433            yield item, parent, key
434            if prune and prune(item, parent, key):
435                continue
436
437            for k, v in item.iter_expressions():
438                queue.append((v, item, k))

Returns a generator object which visits all nodes in this tree in the BFS (Breadth-first) order.

Returns:

The generator object.

def unnest(self):
440    def unnest(self):
441        """
442        Returns the first non parenthesis child or self.
443        """
444        expression = self
445        while type(expression) is Paren:
446            expression = expression.this
447        return expression

Returns the first non parenthesis child or self.

def unalias(self):
449    def unalias(self):
450        """
451        Returns the inner expression if this is an Alias.
452        """
453        if isinstance(self, Alias):
454            return self.this
455        return self

Returns the inner expression if this is an Alias.

def unnest_operands(self):
457    def unnest_operands(self):
458        """
459        Returns unnested operands as a tuple.
460        """
461        return tuple(arg.unnest() for _, arg in self.iter_expressions())

Returns unnested operands as a tuple.

def flatten(self, unnest=True):
463    def flatten(self, unnest=True):
464        """
465        Returns a generator which yields child nodes who's parents are the same class.
466
467        A AND B AND C -> [A, B, C]
468        """
469        for node, _, _ in self.dfs(prune=lambda n, p, *_: p and not type(n) is self.__class__):
470            if not type(node) is self.__class__:
471                yield node.unnest() if unnest else node

Returns a generator which yields child nodes who's parents are the same class.

A AND B AND C -> [A, B, C]

def sql( self, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> str:
479    def sql(self, dialect: DialectType = None, **opts) -> str:
480        """
481        Returns SQL string representation of this tree.
482
483        Args:
484            dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
485            opts: other `sqlglot.generator.Generator` options.
486
487        Returns:
488            The SQL string.
489        """
490        from sqlglot.dialects import Dialect
491
492        return Dialect.get_or_raise(dialect)().generate(self, **opts)

Returns SQL string representation of this tree.

Arguments:
  • dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
  • opts: other sqlglot.generator.Generator options.
Returns:

The SQL string.

def transform(self, fun, *args, copy=True, **kwargs):
518    def transform(self, fun, *args, copy=True, **kwargs):
519        """
520        Recursively visits all tree nodes (excluding already transformed ones)
521        and applies the given transformation function to each node.
522
523        Args:
524            fun (function): a function which takes a node as an argument and returns a
525                new transformed node or the same node without modifications. If the function
526                returns None, then the corresponding node will be removed from the syntax tree.
527            copy (bool): if set to True a new tree instance is constructed, otherwise the tree is
528                modified in place.
529
530        Returns:
531            The transformed tree.
532        """
533        node = self.copy() if copy else self
534        new_node = fun(node, *args, **kwargs)
535
536        if new_node is None or not isinstance(new_node, Expression):
537            return new_node
538        if new_node is not node:
539            new_node.parent = node.parent
540            return new_node
541
542        replace_children(new_node, lambda child: child.transform(fun, *args, copy=False, **kwargs))
543        return new_node

Recursively visits all tree nodes (excluding already transformed ones) and applies the given transformation function to each node.

Arguments:
  • fun (function): a function which takes a node as an argument and returns a new transformed node or the same node without modifications. If the function returns None, then the corresponding node will be removed from the syntax tree.
  • copy (bool): if set to True a new tree instance is constructed, otherwise the tree is modified in place.
Returns:

The transformed tree.

def replace(self, expression):
545    def replace(self, expression):
546        """
547        Swap out this expression with a new expression.
548
549        For example::
550
551            >>> tree = Select().select("x").from_("tbl")
552            >>> tree.find(Column).replace(Column(this="y"))
553            (COLUMN this: y)
554            >>> tree.sql()
555            'SELECT y FROM tbl'
556
557        Args:
558            expression (Expression|None): new node
559
560        Returns:
561            The new expression or expressions.
562        """
563        if not self.parent:
564            return expression
565
566        parent = self.parent
567        self.parent = None
568
569        replace_children(parent, lambda child: expression if child is self else child)
570        return expression

Swap out this expression with a new expression.

For example::

>>> tree = Select().select("x").from_("tbl")
>>> tree.find(Column).replace(Column(this="y"))
(COLUMN this: y)
>>> tree.sql()
'SELECT y FROM tbl'
Arguments:
  • expression (Expression|None): new node
Returns:

The new expression or expressions.

def pop(self):
572    def pop(self):
573        """
574        Remove this expression from its AST.
575
576        Returns:
577            The popped expression.
578        """
579        self.replace(None)
580        return self

Remove this expression from its AST.

Returns:

The popped expression.

def assert_is(self, type_):
582    def assert_is(self, type_):
583        """
584        Assert that this `Expression` is an instance of `type_`.
585
586        If it is NOT an instance of `type_`, this raises an assertion error.
587        Otherwise, this returns this expression.
588
589        Examples:
590            This is useful for type security in chained expressions:
591
592            >>> import sqlglot
593            >>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql()
594            'SELECT x, z FROM y'
595        """
596        assert isinstance(self, type_)
597        return self

Assert that this Expression is an instance of type_.

If it is NOT an instance of type_, this raises an assertion error. Otherwise, this returns this expression.

Examples:

This is useful for type security in chained expressions:

>>> import sqlglot
>>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql()
'SELECT x, z FROM y'
def error_messages(self, args: Optional[Sequence] = None) -> List[str]:
599    def error_messages(self, args: t.Optional[t.Sequence] = None) -> t.List[str]:
600        """
601        Checks if this expression is valid (e.g. all mandatory args are set).
602
603        Args:
604            args: a sequence of values that were used to instantiate a Func expression. This is used
605                to check that the provided arguments don't exceed the function argument limit.
606
607        Returns:
608            A list of error messages for all possible errors that were found.
609        """
610        errors: t.List[str] = []
611
612        for k in self.args:
613            if k not in self.arg_types:
614                errors.append(f"Unexpected keyword: '{k}' for {self.__class__}")
615        for k, mandatory in self.arg_types.items():
616            v = self.args.get(k)
617            if mandatory and (v is None or (isinstance(v, list) and not v)):
618                errors.append(f"Required keyword: '{k}' missing for {self.__class__}")
619
620        if (
621            args
622            and isinstance(self, Func)
623            and len(args) > len(self.arg_types)
624            and not self.is_var_len_args
625        ):
626            errors.append(
627                f"The number of provided arguments ({len(args)}) is greater than "
628                f"the maximum number of supported arguments ({len(self.arg_types)})"
629            )
630
631        return errors

Checks if this expression is valid (e.g. all mandatory args are set).

Arguments:
  • args: a sequence of values that were used to instantiate a Func expression. This is used to check that the provided arguments don't exceed the function argument limit.
Returns:

A list of error messages for all possible errors that were found.

def dump(self):
633    def dump(self):
634        """
635        Dump this Expression to a JSON-serializable dict.
636        """
637        from sqlglot.serde import dump
638
639        return dump(self)

Dump this Expression to a JSON-serializable dict.

@classmethod
def load(cls, obj):
641    @classmethod
642    def load(cls, obj):
643        """
644        Load a dict (as returned by `Expression.dump`) into an Expression instance.
645        """
646        from sqlglot.serde import load
647
648        return load(obj)

Load a dict (as returned by Expression.dump) into an Expression instance.

class Condition(Expression):
659class Condition(Expression):
660    def and_(self, *expressions, dialect=None, copy=True, **opts):
661        """
662        AND this condition with one or multiple expressions.
663
664        Example:
665            >>> condition("x=1").and_("y=1").sql()
666            'x = 1 AND y = 1'
667
668        Args:
669            *expressions (str | Expression): the SQL code strings to parse.
670                If an `Expression` instance is passed, it will be used as-is.
671            dialect (str): the dialect used to parse the input expression.
672            copy (bool): whether or not to copy the involved expressions (only applies to Expressions).
673            opts (kwargs): other options to use to parse the input expressions.
674
675        Returns:
676            And: the new condition.
677        """
678        return and_(self, *expressions, dialect=dialect, copy=copy, **opts)
679
680    def or_(self, *expressions, dialect=None, copy=True, **opts):
681        """
682        OR this condition with one or multiple expressions.
683
684        Example:
685            >>> condition("x=1").or_("y=1").sql()
686            'x = 1 OR y = 1'
687
688        Args:
689            *expressions (str | Expression): the SQL code strings to parse.
690                If an `Expression` instance is passed, it will be used as-is.
691            dialect (str): the dialect used to parse the input expression.
692            copy (bool): whether or not to copy the involved expressions (only applies to Expressions).
693            opts (kwargs): other options to use to parse the input expressions.
694
695        Returns:
696            Or: the new condition.
697        """
698        return or_(self, *expressions, dialect=dialect, copy=copy, **opts)
699
700    def not_(self, copy=True):
701        """
702        Wrap this condition with NOT.
703
704        Example:
705            >>> condition("x=1").not_().sql()
706            'NOT x = 1'
707
708        Args:
709            copy (bool): whether or not to copy this object.
710
711        Returns:
712            Not: the new condition.
713        """
714        return not_(self, copy=copy)
715
716    def _binop(self, klass: t.Type[E], other: t.Any, reverse: bool = False) -> E:
717        this = self.copy()
718        other = convert(other, copy=True)
719        if not isinstance(this, klass) and not isinstance(other, klass):
720            this = _wrap(this, Binary)
721            other = _wrap(other, Binary)
722        if reverse:
723            return klass(this=other, expression=this)
724        return klass(this=this, expression=other)
725
726    def __getitem__(self, other: ExpOrStr | t.Tuple[ExpOrStr]):
727        return Bracket(
728            this=self.copy(), expressions=[convert(e, copy=True) for e in ensure_list(other)]
729        )
730
731    def isin(
732        self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy=True, **opts
733    ) -> In:
734        return In(
735            this=_maybe_copy(self, copy),
736            expressions=[convert(e, copy=copy) for e in expressions],
737            query=maybe_parse(query, copy=copy, **opts) if query else None,
738        )
739
740    def between(self, low: t.Any, high: t.Any, copy=True, **opts) -> Between:
741        return Between(
742            this=_maybe_copy(self, copy),
743            low=convert(low, copy=copy, **opts),
744            high=convert(high, copy=copy, **opts),
745        )
746
747    def like(self, other: ExpOrStr) -> Like:
748        return self._binop(Like, other)
749
750    def ilike(self, other: ExpOrStr) -> ILike:
751        return self._binop(ILike, other)
752
753    def eq(self, other: t.Any) -> EQ:
754        return self._binop(EQ, other)
755
756    def neq(self, other: t.Any) -> NEQ:
757        return self._binop(NEQ, other)
758
759    def rlike(self, other: ExpOrStr) -> RegexpLike:
760        return self._binop(RegexpLike, other)
761
762    def __lt__(self, other: t.Any) -> LT:
763        return self._binop(LT, other)
764
765    def __le__(self, other: t.Any) -> LTE:
766        return self._binop(LTE, other)
767
768    def __gt__(self, other: t.Any) -> GT:
769        return self._binop(GT, other)
770
771    def __ge__(self, other: t.Any) -> GTE:
772        return self._binop(GTE, other)
773
774    def __add__(self, other: t.Any) -> Add:
775        return self._binop(Add, other)
776
777    def __radd__(self, other: t.Any) -> Add:
778        return self._binop(Add, other, reverse=True)
779
780    def __sub__(self, other: t.Any) -> Sub:
781        return self._binop(Sub, other)
782
783    def __rsub__(self, other: t.Any) -> Sub:
784        return self._binop(Sub, other, reverse=True)
785
786    def __mul__(self, other: t.Any) -> Mul:
787        return self._binop(Mul, other)
788
789    def __rmul__(self, other: t.Any) -> Mul:
790        return self._binop(Mul, other, reverse=True)
791
792    def __truediv__(self, other: t.Any) -> Div:
793        return self._binop(Div, other)
794
795    def __rtruediv__(self, other: t.Any) -> Div:
796        return self._binop(Div, other, reverse=True)
797
798    def __floordiv__(self, other: t.Any) -> IntDiv:
799        return self._binop(IntDiv, other)
800
801    def __rfloordiv__(self, other: t.Any) -> IntDiv:
802        return self._binop(IntDiv, other, reverse=True)
803
804    def __mod__(self, other: t.Any) -> Mod:
805        return self._binop(Mod, other)
806
807    def __rmod__(self, other: t.Any) -> Mod:
808        return self._binop(Mod, other, reverse=True)
809
810    def __pow__(self, other: t.Any) -> Pow:
811        return self._binop(Pow, other)
812
813    def __rpow__(self, other: t.Any) -> Pow:
814        return self._binop(Pow, other, reverse=True)
815
816    def __and__(self, other: t.Any) -> And:
817        return self._binop(And, other)
818
819    def __rand__(self, other: t.Any) -> And:
820        return self._binop(And, other, reverse=True)
821
822    def __or__(self, other: t.Any) -> Or:
823        return self._binop(Or, other)
824
825    def __ror__(self, other: t.Any) -> Or:
826        return self._binop(Or, other, reverse=True)
827
828    def __neg__(self) -> Neg:
829        return Neg(this=_wrap(self.copy(), Binary))
830
831    def __invert__(self) -> Not:
832        return not_(self.copy())
def and_(self, *expressions, dialect=None, copy=True, **opts):
660    def and_(self, *expressions, dialect=None, copy=True, **opts):
661        """
662        AND this condition with one or multiple expressions.
663
664        Example:
665            >>> condition("x=1").and_("y=1").sql()
666            'x = 1 AND y = 1'
667
668        Args:
669            *expressions (str | Expression): the SQL code strings to parse.
670                If an `Expression` instance is passed, it will be used as-is.
671            dialect (str): the dialect used to parse the input expression.
672            copy (bool): whether or not to copy the involved expressions (only applies to Expressions).
673            opts (kwargs): other options to use to parse the input expressions.
674
675        Returns:
676            And: the new condition.
677        """
678        return and_(self, *expressions, dialect=dialect, copy=copy, **opts)

AND this condition with one or multiple expressions.

Example:
>>> condition("x=1").and_("y=1").sql()
'x = 1 AND y = 1'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): whether or not to copy the involved expressions (only applies to Expressions).
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

And: the new condition.

def or_(self, *expressions, dialect=None, copy=True, **opts):
680    def or_(self, *expressions, dialect=None, copy=True, **opts):
681        """
682        OR this condition with one or multiple expressions.
683
684        Example:
685            >>> condition("x=1").or_("y=1").sql()
686            'x = 1 OR y = 1'
687
688        Args:
689            *expressions (str | Expression): the SQL code strings to parse.
690                If an `Expression` instance is passed, it will be used as-is.
691            dialect (str): the dialect used to parse the input expression.
692            copy (bool): whether or not to copy the involved expressions (only applies to Expressions).
693            opts (kwargs): other options to use to parse the input expressions.
694
695        Returns:
696            Or: the new condition.
697        """
698        return or_(self, *expressions, dialect=dialect, copy=copy, **opts)

OR this condition with one or multiple expressions.

Example:
>>> condition("x=1").or_("y=1").sql()
'x = 1 OR y = 1'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): whether or not to copy the involved expressions (only applies to Expressions).
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Or: the new condition.

def not_(self, copy=True):
700    def not_(self, copy=True):
701        """
702        Wrap this condition with NOT.
703
704        Example:
705            >>> condition("x=1").not_().sql()
706            'NOT x = 1'
707
708        Args:
709            copy (bool): whether or not to copy this object.
710
711        Returns:
712            Not: the new condition.
713        """
714        return not_(self, copy=copy)

Wrap this condition with NOT.

Example:
>>> condition("x=1").not_().sql()
'NOT x = 1'
Arguments:
  • copy (bool): whether or not to copy this object.
Returns:

Not: the new condition.

def isin( self, *expressions: Any, query: Union[str, sqlglot.expressions.Expression, NoneType] = None, copy=True, **opts) -> sqlglot.expressions.In:
731    def isin(
732        self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy=True, **opts
733    ) -> In:
734        return In(
735            this=_maybe_copy(self, copy),
736            expressions=[convert(e, copy=copy) for e in expressions],
737            query=maybe_parse(query, copy=copy, **opts) if query else None,
738        )
def between( self, low: Any, high: Any, copy=True, **opts) -> sqlglot.expressions.Between:
740    def between(self, low: t.Any, high: t.Any, copy=True, **opts) -> Between:
741        return Between(
742            this=_maybe_copy(self, copy),
743            low=convert(low, copy=copy, **opts),
744            high=convert(high, copy=copy, **opts),
745        )
def like( self, other: Union[str, sqlglot.expressions.Expression]) -> sqlglot.expressions.Like:
747    def like(self, other: ExpOrStr) -> Like:
748        return self._binop(Like, other)
def ilike( self, other: Union[str, sqlglot.expressions.Expression]) -> sqlglot.expressions.ILike:
750    def ilike(self, other: ExpOrStr) -> ILike:
751        return self._binop(ILike, other)
def eq(self, other: Any) -> sqlglot.expressions.EQ:
753    def eq(self, other: t.Any) -> EQ:
754        return self._binop(EQ, other)
def neq(self, other: Any) -> sqlglot.expressions.NEQ:
756    def neq(self, other: t.Any) -> NEQ:
757        return self._binop(NEQ, other)
def rlike( self, other: Union[str, sqlglot.expressions.Expression]) -> sqlglot.expressions.RegexpLike:
759    def rlike(self, other: ExpOrStr) -> RegexpLike:
760        return self._binop(RegexpLike, other)
class Predicate(Condition):
835class Predicate(Condition):
836    """Relationships like x = y, x > 1, x >= y."""

Relationships like x = y, x > 1, x >= y.

class DerivedTable(Expression):
839class DerivedTable(Expression):
840    @property
841    def alias_column_names(self):
842        table_alias = self.args.get("alias")
843        if not table_alias:
844            return []
845        column_list = table_alias.assert_is(TableAlias).args.get("columns") or []
846        return [c.name for c in column_list]
847
848    @property
849    def selects(self):
850        return self.this.selects if isinstance(self.this, Subqueryable) else []
851
852    @property
853    def named_selects(self):
854        return [select.output_name for select in self.selects]
class Unionable(Expression):
857class Unionable(Expression):
858    def union(self, expression, distinct=True, dialect=None, **opts):
859        """
860        Builds a UNION expression.
861
862        Example:
863            >>> import sqlglot
864            >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
865            'SELECT * FROM foo UNION SELECT * FROM bla'
866
867        Args:
868            expression (str | Expression): the SQL code string.
869                If an `Expression` instance is passed, it will be used as-is.
870            distinct (bool): set the DISTINCT flag if and only if this is true.
871            dialect (str): the dialect used to parse the input expression.
872            opts (kwargs): other options to use to parse the input expressions.
873        Returns:
874            Union: the Union expression.
875        """
876        return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
877
878    def intersect(self, expression, distinct=True, dialect=None, **opts):
879        """
880        Builds an INTERSECT expression.
881
882        Example:
883            >>> import sqlglot
884            >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
885            'SELECT * FROM foo INTERSECT SELECT * FROM bla'
886
887        Args:
888            expression (str | Expression): the SQL code string.
889                If an `Expression` instance is passed, it will be used as-is.
890            distinct (bool): set the DISTINCT flag if and only if this is true.
891            dialect (str): the dialect used to parse the input expression.
892            opts (kwargs): other options to use to parse the input expressions.
893        Returns:
894            Intersect: the Intersect expression
895        """
896        return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
897
898    def except_(self, expression, distinct=True, dialect=None, **opts):
899        """
900        Builds an EXCEPT expression.
901
902        Example:
903            >>> import sqlglot
904            >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
905            'SELECT * FROM foo EXCEPT SELECT * FROM bla'
906
907        Args:
908            expression (str | Expression): the SQL code string.
909                If an `Expression` instance is passed, it will be used as-is.
910            distinct (bool): set the DISTINCT flag if and only if this is true.
911            dialect (str): the dialect used to parse the input expression.
912            opts (kwargs): other options to use to parse the input expressions.
913        Returns:
914            Except: the Except expression
915        """
916        return except_(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
def union(self, expression, distinct=True, dialect=None, **opts):
858    def union(self, expression, distinct=True, dialect=None, **opts):
859        """
860        Builds a UNION expression.
861
862        Example:
863            >>> import sqlglot
864            >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
865            'SELECT * FROM foo UNION SELECT * FROM bla'
866
867        Args:
868            expression (str | Expression): the SQL code string.
869                If an `Expression` instance is passed, it will be used as-is.
870            distinct (bool): set the DISTINCT flag if and only if this is true.
871            dialect (str): the dialect used to parse the input expression.
872            opts (kwargs): other options to use to parse the input expressions.
873        Returns:
874            Union: the Union expression.
875        """
876        return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)

Builds a UNION expression.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
'SELECT * FROM foo UNION SELECT * FROM bla'
Arguments:
  • expression (str | Expression): the SQL code string. If an Expression instance is passed, it will be used as-is.
  • distinct (bool): set the DISTINCT flag if and only if this is true.
  • dialect (str): the dialect used to parse the input expression.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Union: the Union expression.

def intersect(self, expression, distinct=True, dialect=None, **opts):
878    def intersect(self, expression, distinct=True, dialect=None, **opts):
879        """
880        Builds an INTERSECT expression.
881
882        Example:
883            >>> import sqlglot
884            >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
885            'SELECT * FROM foo INTERSECT SELECT * FROM bla'
886
887        Args:
888            expression (str | Expression): the SQL code string.
889                If an `Expression` instance is passed, it will be used as-is.
890            distinct (bool): set the DISTINCT flag if and only if this is true.
891            dialect (str): the dialect used to parse the input expression.
892            opts (kwargs): other options to use to parse the input expressions.
893        Returns:
894            Intersect: the Intersect expression
895        """
896        return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)

Builds an INTERSECT expression.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
'SELECT * FROM foo INTERSECT SELECT * FROM bla'
Arguments:
  • expression (str | Expression): the SQL code string. If an Expression instance is passed, it will be used as-is.
  • distinct (bool): set the DISTINCT flag if and only if this is true.
  • dialect (str): the dialect used to parse the input expression.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Intersect: the Intersect expression

def except_(self, expression, distinct=True, dialect=None, **opts):
898    def except_(self, expression, distinct=True, dialect=None, **opts):
899        """
900        Builds an EXCEPT expression.
901
902        Example:
903            >>> import sqlglot
904            >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
905            'SELECT * FROM foo EXCEPT SELECT * FROM bla'
906
907        Args:
908            expression (str | Expression): the SQL code string.
909                If an `Expression` instance is passed, it will be used as-is.
910            distinct (bool): set the DISTINCT flag if and only if this is true.
911            dialect (str): the dialect used to parse the input expression.
912            opts (kwargs): other options to use to parse the input expressions.
913        Returns:
914            Except: the Except expression
915        """
916        return except_(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)

Builds an EXCEPT expression.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
'SELECT * FROM foo EXCEPT SELECT * FROM bla'
Arguments:
  • expression (str | Expression): the SQL code string. If an Expression instance is passed, it will be used as-is.
  • distinct (bool): set the DISTINCT flag if and only if this is true.
  • dialect (str): the dialect used to parse the input expression.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Except: the Except expression

class UDTF(DerivedTable, Unionable):
919class UDTF(DerivedTable, Unionable):
920    @property
921    def selects(self):
922        alias = self.args.get("alias")
923        return alias.columns if alias else []
class Cache(Expression):
926class Cache(Expression):
927    arg_types = {
928        "with": False,
929        "this": True,
930        "lazy": False,
931        "options": False,
932        "expression": False,
933    }
class Uncache(Expression):
936class Uncache(Expression):
937    arg_types = {"this": True, "exists": False}
class Create(Expression):
940class Create(Expression):
941    arg_types = {
942        "with": False,
943        "this": True,
944        "kind": True,
945        "expression": False,
946        "exists": False,
947        "properties": False,
948        "replace": False,
949        "unique": False,
950        "indexes": False,
951        "no_schema_binding": False,
952        "begin": False,
953    }
class Describe(Expression):
956class Describe(Expression):
957    arg_types = {"this": True, "kind": False}
class Pragma(Expression):
960class Pragma(Expression):
961    pass
class Set(Expression):
964class Set(Expression):
965    arg_types = {"expressions": False}
class SetItem(Expression):
968class SetItem(Expression):
969    arg_types = {
970        "this": False,
971        "expressions": False,
972        "kind": False,
973        "collate": False,  # MySQL SET NAMES statement
974        "global": False,
975    }
class Show(Expression):
978class Show(Expression):
979    arg_types = {
980        "this": True,
981        "target": False,
982        "offset": False,
983        "limit": False,
984        "like": False,
985        "where": False,
986        "db": False,
987        "full": False,
988        "mutex": False,
989        "query": False,
990        "channel": False,
991        "global": False,
992        "log": False,
993        "position": False,
994        "types": False,
995    }
class UserDefinedFunction(Expression):
998class UserDefinedFunction(Expression):
999    arg_types = {"this": True, "expressions": False, "wrapped": False}
class CharacterSet(Expression):
1002class CharacterSet(Expression):
1003    arg_types = {"this": True, "default": False}
class With(Expression):
1006class With(Expression):
1007    arg_types = {"expressions": True, "recursive": False}
1008
1009    @property
1010    def recursive(self) -> bool:
1011        return bool(self.args.get("recursive"))
class WithinGroup(Expression):
1014class WithinGroup(Expression):
1015    arg_types = {"this": True, "expression": False}
class CTE(DerivedTable):
1018class CTE(DerivedTable):
1019    arg_types = {"this": True, "alias": True}
class TableAlias(Expression):
1022class TableAlias(Expression):
1023    arg_types = {"this": False, "columns": False}
1024
1025    @property
1026    def columns(self):
1027        return self.args.get("columns") or []
class BitString(Condition):
1030class BitString(Condition):
1031    pass
class HexString(Condition):
1034class HexString(Condition):
1035    pass
class ByteString(Condition):
1038class ByteString(Condition):
1039    pass
class Column(Condition):
1042class Column(Condition):
1043    arg_types = {"this": True, "table": False, "db": False, "catalog": False, "join_mark": False}
1044
1045    @property
1046    def table(self) -> str:
1047        return self.text("table")
1048
1049    @property
1050    def db(self) -> str:
1051        return self.text("db")
1052
1053    @property
1054    def catalog(self) -> str:
1055        return self.text("catalog")
1056
1057    @property
1058    def output_name(self) -> str:
1059        return self.name
1060
1061    @property
1062    def parts(self) -> t.List[Identifier]:
1063        """Return the parts of a column in order catalog, db, table, name."""
1064        return [
1065            t.cast(Identifier, self.args[part])
1066            for part in ("catalog", "db", "table", "this")
1067            if self.args.get(part)
1068        ]
1069
1070    def to_dot(self) -> Dot:
1071        """Converts the column into a dot expression."""
1072        parts = self.parts
1073        parent = self.parent
1074
1075        while parent:
1076            if isinstance(parent, Dot):
1077                parts.append(parent.expression)
1078            parent = parent.parent
1079
1080        return Dot.build(parts)
output_name: str

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''

Return the parts of a column in order catalog, db, table, name.

def to_dot(self) -> sqlglot.expressions.Dot:
1070    def to_dot(self) -> Dot:
1071        """Converts the column into a dot expression."""
1072        parts = self.parts
1073        parent = self.parent
1074
1075        while parent:
1076            if isinstance(parent, Dot):
1077                parts.append(parent.expression)
1078            parent = parent.parent
1079
1080        return Dot.build(parts)

Converts the column into a dot expression.

class ColumnPosition(Expression):
1083class ColumnPosition(Expression):
1084    arg_types = {"this": False, "position": True}
class ColumnDef(Expression):
1087class ColumnDef(Expression):
1088    arg_types = {
1089        "this": True,
1090        "kind": False,
1091        "constraints": False,
1092        "exists": False,
1093        "position": False,
1094    }
1095
1096    @property
1097    def constraints(self) -> t.List[ColumnConstraint]:
1098        return self.args.get("constraints") or []
class AlterColumn(Expression):
1101class AlterColumn(Expression):
1102    arg_types = {
1103        "this": True,
1104        "dtype": False,
1105        "collate": False,
1106        "using": False,
1107        "default": False,
1108        "drop": False,
1109    }
class RenameTable(Expression):
1112class RenameTable(Expression):
1113    pass
class SetTag(Expression):
1116class SetTag(Expression):
1117    arg_types = {"expressions": True, "unset": False}
class Comment(Expression):
1120class Comment(Expression):
1121    arg_types = {"this": True, "kind": True, "expression": True, "exists": False}
class MergeTreeTTLAction(Expression):
1125class MergeTreeTTLAction(Expression):
1126    arg_types = {
1127        "this": True,
1128        "delete": False,
1129        "recompress": False,
1130        "to_disk": False,
1131        "to_volume": False,
1132    }
class MergeTreeTTL(Expression):
1136class MergeTreeTTL(Expression):
1137    arg_types = {
1138        "expressions": True,
1139        "where": False,
1140        "group": False,
1141        "aggregates": False,
1142    }
class ColumnConstraint(Expression):
1145class ColumnConstraint(Expression):
1146    arg_types = {"this": False, "kind": True}
1147
1148    @property
1149    def kind(self) -> ColumnConstraintKind:
1150        return self.args["kind"]
class ColumnConstraintKind(Expression):
1153class ColumnConstraintKind(Expression):
1154    pass
class AutoIncrementColumnConstraint(ColumnConstraintKind):
1157class AutoIncrementColumnConstraint(ColumnConstraintKind):
1158    pass
class CaseSpecificColumnConstraint(ColumnConstraintKind):
1161class CaseSpecificColumnConstraint(ColumnConstraintKind):
1162    arg_types = {"not_": True}
class CharacterSetColumnConstraint(ColumnConstraintKind):
1165class CharacterSetColumnConstraint(ColumnConstraintKind):
1166    arg_types = {"this": True}
class CheckColumnConstraint(ColumnConstraintKind):
1169class CheckColumnConstraint(ColumnConstraintKind):
1170    pass
class CollateColumnConstraint(ColumnConstraintKind):
1173class CollateColumnConstraint(ColumnConstraintKind):
1174    pass
class CommentColumnConstraint(ColumnConstraintKind):
1177class CommentColumnConstraint(ColumnConstraintKind):
1178    pass
class CompressColumnConstraint(ColumnConstraintKind):
1181class CompressColumnConstraint(ColumnConstraintKind):
1182    pass
class DateFormatColumnConstraint(ColumnConstraintKind):
1185class DateFormatColumnConstraint(ColumnConstraintKind):
1186    arg_types = {"this": True}
class DefaultColumnConstraint(ColumnConstraintKind):
1189class DefaultColumnConstraint(ColumnConstraintKind):
1190    pass
class EncodeColumnConstraint(ColumnConstraintKind):
1193class EncodeColumnConstraint(ColumnConstraintKind):
1194    pass
class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind):
1197class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind):
1198    # this: True -> ALWAYS, this: False -> BY DEFAULT
1199    arg_types = {
1200        "this": False,
1201        "on_null": False,
1202        "start": False,
1203        "increment": False,
1204        "minvalue": False,
1205        "maxvalue": False,
1206        "cycle": False,
1207    }
class InlineLengthColumnConstraint(ColumnConstraintKind):
1210class InlineLengthColumnConstraint(ColumnConstraintKind):
1211    pass
class NotNullColumnConstraint(ColumnConstraintKind):
1214class NotNullColumnConstraint(ColumnConstraintKind):
1215    arg_types = {"allow_null": False}
class OnUpdateColumnConstraint(ColumnConstraintKind):
1219class OnUpdateColumnConstraint(ColumnConstraintKind):
1220    pass
class PrimaryKeyColumnConstraint(ColumnConstraintKind):
1223class PrimaryKeyColumnConstraint(ColumnConstraintKind):
1224    arg_types = {"desc": False}
class TitleColumnConstraint(ColumnConstraintKind):
1227class TitleColumnConstraint(ColumnConstraintKind):
1228    pass
class UniqueColumnConstraint(ColumnConstraintKind):
1231class UniqueColumnConstraint(ColumnConstraintKind):
1232    arg_types: t.Dict[str, t.Any] = {}
class UppercaseColumnConstraint(ColumnConstraintKind):
1235class UppercaseColumnConstraint(ColumnConstraintKind):
1236    arg_types: t.Dict[str, t.Any] = {}
class PathColumnConstraint(ColumnConstraintKind):
1239class PathColumnConstraint(ColumnConstraintKind):
1240    pass
class Constraint(Expression):
1243class Constraint(Expression):
1244    arg_types = {"this": True, "expressions": True}
class Delete(Expression):
1247class Delete(Expression):
1248    arg_types = {"with": False, "this": False, "using": False, "where": False, "returning": False}
1249
1250    def delete(
1251        self,
1252        table: ExpOrStr,
1253        dialect: DialectType = None,
1254        copy: bool = True,
1255        **opts,
1256    ) -> Delete:
1257        """
1258        Create a DELETE expression or replace the table on an existing DELETE expression.
1259
1260        Example:
1261            >>> delete("tbl").sql()
1262            'DELETE FROM tbl'
1263
1264        Args:
1265            table: the table from which to delete.
1266            dialect: the dialect used to parse the input expression.
1267            copy: if `False`, modify this expression instance in-place.
1268            opts: other options to use to parse the input expressions.
1269
1270        Returns:
1271            Delete: the modified expression.
1272        """
1273        return _apply_builder(
1274            expression=table,
1275            instance=self,
1276            arg="this",
1277            dialect=dialect,
1278            into=Table,
1279            copy=copy,
1280            **opts,
1281        )
1282
1283    def where(
1284        self,
1285        *expressions: ExpOrStr,
1286        append: bool = True,
1287        dialect: DialectType = None,
1288        copy: bool = True,
1289        **opts,
1290    ) -> Delete:
1291        """
1292        Append to or set the WHERE expressions.
1293
1294        Example:
1295            >>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
1296            "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
1297
1298        Args:
1299            *expressions: the SQL code strings to parse.
1300                If an `Expression` instance is passed, it will be used as-is.
1301                Multiple expressions are combined with an AND operator.
1302            append: if `True`, AND the new expressions to any existing expression.
1303                Otherwise, this resets the expression.
1304            dialect: the dialect used to parse the input expressions.
1305            copy: if `False`, modify this expression instance in-place.
1306            opts: other options to use to parse the input expressions.
1307
1308        Returns:
1309            Delete: the modified expression.
1310        """
1311        return _apply_conjunction_builder(
1312            *expressions,
1313            instance=self,
1314            arg="where",
1315            append=append,
1316            into=Where,
1317            dialect=dialect,
1318            copy=copy,
1319            **opts,
1320        )
1321
1322    def returning(
1323        self,
1324        expression: ExpOrStr,
1325        dialect: DialectType = None,
1326        copy: bool = True,
1327        **opts,
1328    ) -> Delete:
1329        """
1330        Set the RETURNING expression. Not supported by all dialects.
1331
1332        Example:
1333            >>> delete("tbl").returning("*", dialect="postgres").sql()
1334            'DELETE FROM tbl RETURNING *'
1335
1336        Args:
1337            expression: the SQL code strings to parse.
1338                If an `Expression` instance is passed, it will be used as-is.
1339            dialect: the dialect used to parse the input expressions.
1340            copy: if `False`, modify this expression instance in-place.
1341            opts: other options to use to parse the input expressions.
1342
1343        Returns:
1344            Delete: the modified expression.
1345        """
1346        return _apply_builder(
1347            expression=expression,
1348            instance=self,
1349            arg="returning",
1350            prefix="RETURNING",
1351            dialect=dialect,
1352            copy=copy,
1353            into=Returning,
1354            **opts,
1355        )
def delete( self, table: Union[str, sqlglot.expressions.Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Delete:
1250    def delete(
1251        self,
1252        table: ExpOrStr,
1253        dialect: DialectType = None,
1254        copy: bool = True,
1255        **opts,
1256    ) -> Delete:
1257        """
1258        Create a DELETE expression or replace the table on an existing DELETE expression.
1259
1260        Example:
1261            >>> delete("tbl").sql()
1262            'DELETE FROM tbl'
1263
1264        Args:
1265            table: the table from which to delete.
1266            dialect: the dialect used to parse the input expression.
1267            copy: if `False`, modify this expression instance in-place.
1268            opts: other options to use to parse the input expressions.
1269
1270        Returns:
1271            Delete: the modified expression.
1272        """
1273        return _apply_builder(
1274            expression=table,
1275            instance=self,
1276            arg="this",
1277            dialect=dialect,
1278            into=Table,
1279            copy=copy,
1280            **opts,
1281        )

Create a DELETE expression or replace the table on an existing DELETE expression.

Example:
>>> delete("tbl").sql()
'DELETE FROM tbl'
Arguments:
  • table: the table from which to delete.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Delete: the modified expression.

def where( self, *expressions: Union[str, sqlglot.expressions.Expression], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Delete:
1283    def where(
1284        self,
1285        *expressions: ExpOrStr,
1286        append: bool = True,
1287        dialect: DialectType = None,
1288        copy: bool = True,
1289        **opts,
1290    ) -> Delete:
1291        """
1292        Append to or set the WHERE expressions.
1293
1294        Example:
1295            >>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
1296            "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
1297
1298        Args:
1299            *expressions: the SQL code strings to parse.
1300                If an `Expression` instance is passed, it will be used as-is.
1301                Multiple expressions are combined with an AND operator.
1302            append: if `True`, AND the new expressions to any existing expression.
1303                Otherwise, this resets the expression.
1304            dialect: the dialect used to parse the input expressions.
1305            copy: if `False`, modify this expression instance in-place.
1306            opts: other options to use to parse the input expressions.
1307
1308        Returns:
1309            Delete: the modified expression.
1310        """
1311        return _apply_conjunction_builder(
1312            *expressions,
1313            instance=self,
1314            arg="where",
1315            append=append,
1316            into=Where,
1317            dialect=dialect,
1318            copy=copy,
1319            **opts,
1320        )

Append to or set the WHERE expressions.

Example:
>>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
"DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator.
  • append: if True, AND the new expressions to any existing expression. Otherwise, this resets the expression.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Delete: the modified expression.

def returning( self, expression: Union[str, sqlglot.expressions.Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Delete:
1322    def returning(
1323        self,
1324        expression: ExpOrStr,
1325        dialect: DialectType = None,
1326        copy: bool = True,
1327        **opts,
1328    ) -> Delete:
1329        """
1330        Set the RETURNING expression. Not supported by all dialects.
1331
1332        Example:
1333            >>> delete("tbl").returning("*", dialect="postgres").sql()
1334            'DELETE FROM tbl RETURNING *'
1335
1336        Args:
1337            expression: the SQL code strings to parse.
1338                If an `Expression` instance is passed, it will be used as-is.
1339            dialect: the dialect used to parse the input expressions.
1340            copy: if `False`, modify this expression instance in-place.
1341            opts: other options to use to parse the input expressions.
1342
1343        Returns:
1344            Delete: the modified expression.
1345        """
1346        return _apply_builder(
1347            expression=expression,
1348            instance=self,
1349            arg="returning",
1350            prefix="RETURNING",
1351            dialect=dialect,
1352            copy=copy,
1353            into=Returning,
1354            **opts,
1355        )

Set the RETURNING expression. Not supported by all dialects.

Example:
>>> delete("tbl").returning("*", dialect="postgres").sql()
'DELETE FROM tbl RETURNING *'
Arguments:
  • expression: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Delete: the modified expression.

class Drop(Expression):
1358class Drop(Expression):
1359    arg_types = {
1360        "this": False,
1361        "kind": False,
1362        "exists": False,
1363        "temporary": False,
1364        "materialized": False,
1365        "cascade": False,
1366        "constraints": False,
1367        "purge": False,
1368    }
class Filter(Expression):
1371class Filter(Expression):
1372    arg_types = {"this": True, "expression": True}
class Check(Expression):
1375class Check(Expression):
1376    pass
class Directory(Expression):
1379class Directory(Expression):
1380    # https://spark.apache.org/docs/3.0.0-preview/sql-ref-syntax-dml-insert-overwrite-directory-hive.html
1381    arg_types = {"this": True, "local": False, "row_format": False}
class ForeignKey(Expression):
1384class ForeignKey(Expression):
1385    arg_types = {
1386        "expressions": True,
1387        "reference": False,
1388        "delete": False,
1389        "update": False,
1390    }
class PrimaryKey(Expression):
1393class PrimaryKey(Expression):
1394    arg_types = {"expressions": True, "options": False}
class Unique(Expression):
1397class Unique(Expression):
1398    arg_types = {"expressions": True}
class Into(Expression):
1403class Into(Expression):
1404    arg_types = {"this": True, "temporary": False, "unlogged": False}
class From(Expression):
1407class From(Expression):
1408    arg_types = {"expressions": True}
class Having(Expression):
1411class Having(Expression):
1412    pass
class Hint(Expression):
1415class Hint(Expression):
1416    arg_types = {"expressions": True}
class JoinHint(Expression):
1419class JoinHint(Expression):
1420    arg_types = {"this": True, "expressions": True}
class Identifier(Expression):
1423class Identifier(Expression):
1424    arg_types = {"this": True, "quoted": False}
1425
1426    @property
1427    def quoted(self):
1428        return bool(self.args.get("quoted"))
1429
1430    @property
1431    def hashable_args(self) -> t.Any:
1432        if self.quoted and any(char.isupper() for char in self.this):
1433            return (self.this, self.quoted)
1434        return self.this.lower()
1435
1436    @property
1437    def output_name(self):
1438        return self.name
output_name

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
class Index(Expression):
1441class Index(Expression):
1442    arg_types = {
1443        "this": False,
1444        "table": False,
1445        "where": False,
1446        "columns": False,
1447        "unique": False,
1448        "primary": False,
1449        "amp": False,  # teradata
1450    }
class Insert(Expression):
1453class Insert(Expression):
1454    arg_types = {
1455        "with": False,
1456        "this": True,
1457        "expression": False,
1458        "conflict": False,
1459        "returning": False,
1460        "overwrite": False,
1461        "exists": False,
1462        "partition": False,
1463        "alternative": False,
1464    }
class OnConflict(Expression):
1467class OnConflict(Expression):
1468    arg_types = {
1469        "duplicate": False,
1470        "expressions": False,
1471        "nothing": False,
1472        "key": False,
1473        "constraint": False,
1474    }
class Returning(Expression):
1477class Returning(Expression):
1478    arg_types = {"expressions": True}
class Introducer(Expression):
1482class Introducer(Expression):
1483    arg_types = {"this": True, "expression": True}
class National(Expression):
1487class National(Expression):
1488    pass
class LoadData(Expression):
1491class LoadData(Expression):
1492    arg_types = {
1493        "this": True,
1494        "local": False,
1495        "overwrite": False,
1496        "inpath": True,
1497        "partition": False,
1498        "input_format": False,
1499        "serde": False,
1500    }
class Partition(Expression):
1503class Partition(Expression):
1504    arg_types = {"expressions": True}
class Fetch(Expression):
1507class Fetch(Expression):
1508    arg_types = {
1509        "direction": False,
1510        "count": False,
1511        "percent": False,
1512        "with_ties": False,
1513    }
class Group(Expression):
1516class Group(Expression):
1517    arg_types = {
1518        "expressions": False,
1519        "grouping_sets": False,
1520        "cube": False,
1521        "rollup": False,
1522    }
class Lambda(Expression):
1525class Lambda(Expression):
1526    arg_types = {"this": True, "expressions": True}
class Limit(Expression):
1529class Limit(Expression):
1530    arg_types = {"this": False, "expression": True}
class Literal(Condition):
1533class Literal(Condition):
1534    arg_types = {"this": True, "is_string": True}
1535
1536    @property
1537    def hashable_args(self) -> t.Any:
1538        return (self.this, self.args.get("is_string"))
1539
1540    @classmethod
1541    def number(cls, number) -> Literal:
1542        return cls(this=str(number), is_string=False)
1543
1544    @classmethod
1545    def string(cls, string) -> Literal:
1546        return cls(this=str(string), is_string=True)
1547
1548    @property
1549    def output_name(self):
1550        return self.name
@classmethod
def number(cls, number) -> sqlglot.expressions.Literal:
1540    @classmethod
1541    def number(cls, number) -> Literal:
1542        return cls(this=str(number), is_string=False)
@classmethod
def string(cls, string) -> sqlglot.expressions.Literal:
1544    @classmethod
1545    def string(cls, string) -> Literal:
1546        return cls(this=str(string), is_string=True)
output_name

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
class Join(Expression):
1553class Join(Expression):
1554    arg_types = {
1555        "this": True,
1556        "on": False,
1557        "side": False,
1558        "kind": False,
1559        "using": False,
1560        "natural": False,
1561        "hint": False,
1562    }
1563
1564    @property
1565    def kind(self):
1566        return self.text("kind").upper()
1567
1568    @property
1569    def side(self):
1570        return self.text("side").upper()
1571
1572    @property
1573    def hint(self):
1574        return self.text("hint").upper()
1575
1576    @property
1577    def alias_or_name(self):
1578        return self.this.alias_or_name
1579
1580    def on(self, *expressions, append=True, dialect=None, copy=True, **opts):
1581        """
1582        Append to or set the ON expressions.
1583
1584        Example:
1585            >>> import sqlglot
1586            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1587            'JOIN x ON y = 1'
1588
1589        Args:
1590            *expressions (str | Expression): the SQL code strings to parse.
1591                If an `Expression` instance is passed, it will be used as-is.
1592                Multiple expressions are combined with an AND operator.
1593            append (bool): if `True`, AND the new expressions to any existing expression.
1594                Otherwise, this resets the expression.
1595            dialect (str): the dialect used to parse the input expressions.
1596            copy (bool): if `False`, modify this expression instance in-place.
1597            opts (kwargs): other options to use to parse the input expressions.
1598
1599        Returns:
1600            Join: the modified join expression.
1601        """
1602        join = _apply_conjunction_builder(
1603            *expressions,
1604            instance=self,
1605            arg="on",
1606            append=append,
1607            dialect=dialect,
1608            copy=copy,
1609            **opts,
1610        )
1611
1612        if join.kind == "CROSS":
1613            join.set("kind", None)
1614
1615        return join
1616
1617    def using(self, *expressions, append=True, dialect=None, copy=True, **opts):
1618        """
1619        Append to or set the USING expressions.
1620
1621        Example:
1622            >>> import sqlglot
1623            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1624            'JOIN x USING (foo, bla)'
1625
1626        Args:
1627            *expressions (str | Expression): the SQL code strings to parse.
1628                If an `Expression` instance is passed, it will be used as-is.
1629            append (bool): if `True`, concatenate the new expressions to the existing "using" list.
1630                Otherwise, this resets the expression.
1631            dialect (str): the dialect used to parse the input expressions.
1632            copy (bool): if `False`, modify this expression instance in-place.
1633            opts (kwargs): other options to use to parse the input expressions.
1634
1635        Returns:
1636            Join: the modified join expression.
1637        """
1638        join = _apply_list_builder(
1639            *expressions,
1640            instance=self,
1641            arg="using",
1642            append=append,
1643            dialect=dialect,
1644            copy=copy,
1645            **opts,
1646        )
1647
1648        if join.kind == "CROSS":
1649            join.set("kind", None)
1650
1651        return join
def on(self, *expressions, append=True, dialect=None, copy=True, **opts):
1580    def on(self, *expressions, append=True, dialect=None, copy=True, **opts):
1581        """
1582        Append to or set the ON expressions.
1583
1584        Example:
1585            >>> import sqlglot
1586            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1587            'JOIN x ON y = 1'
1588
1589        Args:
1590            *expressions (str | Expression): the SQL code strings to parse.
1591                If an `Expression` instance is passed, it will be used as-is.
1592                Multiple expressions are combined with an AND operator.
1593            append (bool): if `True`, AND the new expressions to any existing expression.
1594                Otherwise, this resets the expression.
1595            dialect (str): the dialect used to parse the input expressions.
1596            copy (bool): if `False`, modify this expression instance in-place.
1597            opts (kwargs): other options to use to parse the input expressions.
1598
1599        Returns:
1600            Join: the modified join expression.
1601        """
1602        join = _apply_conjunction_builder(
1603            *expressions,
1604            instance=self,
1605            arg="on",
1606            append=append,
1607            dialect=dialect,
1608            copy=copy,
1609            **opts,
1610        )
1611
1612        if join.kind == "CROSS":
1613            join.set("kind", None)
1614
1615        return join

Append to or set the ON expressions.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
'JOIN x ON y = 1'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator.
  • append (bool): if True, AND the new expressions to any existing expression. Otherwise, this resets the expression.
  • dialect (str): the dialect used to parse the input expressions.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Join: the modified join expression.

def using(self, *expressions, append=True, dialect=None, copy=True, **opts):
1617    def using(self, *expressions, append=True, dialect=None, copy=True, **opts):
1618        """
1619        Append to or set the USING expressions.
1620
1621        Example:
1622            >>> import sqlglot
1623            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1624            'JOIN x USING (foo, bla)'
1625
1626        Args:
1627            *expressions (str | Expression): the SQL code strings to parse.
1628                If an `Expression` instance is passed, it will be used as-is.
1629            append (bool): if `True`, concatenate the new expressions to the existing "using" list.
1630                Otherwise, this resets the expression.
1631            dialect (str): the dialect used to parse the input expressions.
1632            copy (bool): if `False`, modify this expression instance in-place.
1633            opts (kwargs): other options to use to parse the input expressions.
1634
1635        Returns:
1636            Join: the modified join expression.
1637        """
1638        join = _apply_list_builder(
1639            *expressions,
1640            instance=self,
1641            arg="using",
1642            append=append,
1643            dialect=dialect,
1644            copy=copy,
1645            **opts,
1646        )
1647
1648        if join.kind == "CROSS":
1649            join.set("kind", None)
1650
1651        return join

Append to or set the USING expressions.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
'JOIN x USING (foo, bla)'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • append (bool): if True, concatenate the new expressions to the existing "using" list. Otherwise, this resets the expression.
  • dialect (str): the dialect used to parse the input expressions.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Join: the modified join expression.

class Lateral(UDTF):
1654class Lateral(UDTF):
1655    arg_types = {"this": True, "view": False, "outer": False, "alias": False}
class MatchRecognize(Expression):
1658class MatchRecognize(Expression):
1659    arg_types = {
1660        "partition_by": False,
1661        "order": False,
1662        "measures": False,
1663        "rows": False,
1664        "after": False,
1665        "pattern": False,
1666        "define": False,
1667        "alias": False,
1668    }
class Final(Expression):
1673class Final(Expression):
1674    pass
class Offset(Expression):
1677class Offset(Expression):
1678    arg_types = {"this": False, "expression": True}
class Order(Expression):
1681class Order(Expression):
1682    arg_types = {"this": False, "expressions": True}
class Cluster(Order):
1687class Cluster(Order):
1688    pass
class Distribute(Order):
1691class Distribute(Order):
1692    pass
class Sort(Order):
1695class Sort(Order):
1696    pass
class Ordered(Expression):
1699class Ordered(Expression):
1700    arg_types = {"this": True, "desc": True, "nulls_first": True}
class Property(Expression):
1703class Property(Expression):
1704    arg_types = {"this": True, "value": True}
class AfterJournalProperty(Property):
1707class AfterJournalProperty(Property):
1708    arg_types = {"no": True, "dual": False, "local": False}
class AlgorithmProperty(Property):
1711class AlgorithmProperty(Property):
1712    arg_types = {"this": True}
class AutoIncrementProperty(Property):
1715class AutoIncrementProperty(Property):
1716    arg_types = {"this": True}
class BlockCompressionProperty(Property):
1719class BlockCompressionProperty(Property):
1720    arg_types = {"autotemp": False, "always": False, "default": True, "manual": True, "never": True}
class CharacterSetProperty(Property):
1723class CharacterSetProperty(Property):
1724    arg_types = {"this": True, "default": True}
class ChecksumProperty(Property):
1727class ChecksumProperty(Property):
1728    arg_types = {"on": False, "default": False}
class CollateProperty(Property):
1731class CollateProperty(Property):
1732    arg_types = {"this": True}
class DataBlocksizeProperty(Property):
1735class DataBlocksizeProperty(Property):
1736    arg_types = {"size": False, "units": False, "min": False, "default": False}
class DefinerProperty(Property):
1739class DefinerProperty(Property):
1740    arg_types = {"this": True}
class DistKeyProperty(Property):
1743class DistKeyProperty(Property):
1744    arg_types = {"this": True}
class DistStyleProperty(Property):
1747class DistStyleProperty(Property):
1748    arg_types = {"this": True}
class EngineProperty(Property):
1751class EngineProperty(Property):
1752    arg_types = {"this": True}
class ExecuteAsProperty(Property):
1755class ExecuteAsProperty(Property):
1756    arg_types = {"this": True}
class ExternalProperty(Property):
1759class ExternalProperty(Property):
1760    arg_types = {"this": False}
class FallbackProperty(Property):
1763class FallbackProperty(Property):
1764    arg_types = {"no": True, "protection": False}
class FileFormatProperty(Property):
1767class FileFormatProperty(Property):
1768    arg_types = {"this": True}
class FreespaceProperty(Property):
1771class FreespaceProperty(Property):
1772    arg_types = {"this": True, "percent": False}
class InputOutputFormat(Expression):
1775class InputOutputFormat(Expression):
1776    arg_types = {"input_format": False, "output_format": False}
class IsolatedLoadingProperty(Property):
1779class IsolatedLoadingProperty(Property):
1780    arg_types = {
1781        "no": True,
1782        "concurrent": True,
1783        "for_all": True,
1784        "for_insert": True,
1785        "for_none": True,
1786    }
class JournalProperty(Property):
1789class JournalProperty(Property):
1790    arg_types = {"no": True, "dual": False, "before": False}
class LanguageProperty(Property):
1793class LanguageProperty(Property):
1794    arg_types = {"this": True}
class LikeProperty(Property):
1797class LikeProperty(Property):
1798    arg_types = {"this": True, "expressions": False}
class LocationProperty(Property):
1801class LocationProperty(Property):
1802    arg_types = {"this": True}
class LockingProperty(Property):
1805class LockingProperty(Property):
1806    arg_types = {
1807        "this": False,
1808        "kind": True,
1809        "for_or_in": True,
1810        "lock_type": True,
1811        "override": False,
1812    }
class LogProperty(Property):
1815class LogProperty(Property):
1816    arg_types = {"no": True}
class MaterializedProperty(Property):
1819class MaterializedProperty(Property):
1820    arg_types = {"this": False}
class MergeBlockRatioProperty(Property):
1823class MergeBlockRatioProperty(Property):
1824    arg_types = {"this": False, "no": False, "default": False, "percent": False}
class NoPrimaryIndexProperty(Property):
1827class NoPrimaryIndexProperty(Property):
1828    arg_types = {"this": False}
class OnCommitProperty(Property):
1831class OnCommitProperty(Property):
1832    arg_type = {"this": False}
class PartitionedByProperty(Property):
1835class PartitionedByProperty(Property):
1836    arg_types = {"this": True}
class ReturnsProperty(Property):
1839class ReturnsProperty(Property):
1840    arg_types = {"this": True, "is_table": False, "table": False}
class RowFormatProperty(Property):
1843class RowFormatProperty(Property):
1844    arg_types = {"this": True}
class RowFormatDelimitedProperty(Property):
1847class RowFormatDelimitedProperty(Property):
1848    # https://cwiki.apache.org/confluence/display/hive/languagemanual+dml
1849    arg_types = {
1850        "fields": False,
1851        "escaped": False,
1852        "collection_items": False,
1853        "map_keys": False,
1854        "lines": False,
1855        "null": False,
1856        "serde": False,
1857    }
class RowFormatSerdeProperty(Property):
1860class RowFormatSerdeProperty(Property):
1861    arg_types = {"this": True}
class SchemaCommentProperty(Property):
1864class SchemaCommentProperty(Property):
1865    arg_types = {"this": True}
class SerdeProperties(Property):
1868class SerdeProperties(Property):
1869    arg_types = {"expressions": True}
class SetProperty(Property):
1872class SetProperty(Property):
1873    arg_types = {"multi": True}
class SettingsProperty(Property):
1876class SettingsProperty(Property):
1877    arg_types = {"expressions": True}
class SortKeyProperty(Property):
1880class SortKeyProperty(Property):
1881    arg_types = {"this": True, "compound": False}
class SqlSecurityProperty(Property):
1884class SqlSecurityProperty(Property):
1885    arg_types = {"definer": True}
class StabilityProperty(Property):
1888class StabilityProperty(Property):
1889    arg_types = {"this": True}
class TableFormatProperty(Property):
1892class TableFormatProperty(Property):
1893    arg_types = {"this": True}
class TemporaryProperty(Property):
1896class TemporaryProperty(Property):
1897    arg_types = {"global_": True}
class TransientProperty(Property):
1900class TransientProperty(Property):
1901    arg_types = {"this": False}
class VolatileProperty(Property):
1904class VolatileProperty(Property):
1905    arg_types = {"this": False}
class WithDataProperty(Property):
1908class WithDataProperty(Property):
1909    arg_types = {"no": True, "statistics": False}
class WithJournalTableProperty(Property):
1912class WithJournalTableProperty(Property):
1913    arg_types = {"this": True}
class Properties(Expression):
1916class Properties(Expression):
1917    arg_types = {"expressions": True}
1918
1919    NAME_TO_PROPERTY = {
1920        "ALGORITHM": AlgorithmProperty,
1921        "AUTO_INCREMENT": AutoIncrementProperty,
1922        "CHARACTER SET": CharacterSetProperty,
1923        "COLLATE": CollateProperty,
1924        "COMMENT": SchemaCommentProperty,
1925        "DEFINER": DefinerProperty,
1926        "DISTKEY": DistKeyProperty,
1927        "DISTSTYLE": DistStyleProperty,
1928        "ENGINE": EngineProperty,
1929        "EXECUTE AS": ExecuteAsProperty,
1930        "FORMAT": FileFormatProperty,
1931        "LANGUAGE": LanguageProperty,
1932        "LOCATION": LocationProperty,
1933        "PARTITIONED_BY": PartitionedByProperty,
1934        "RETURNS": ReturnsProperty,
1935        "ROW_FORMAT": RowFormatProperty,
1936        "SORTKEY": SortKeyProperty,
1937        "TABLE_FORMAT": TableFormatProperty,
1938    }
1939
1940    PROPERTY_TO_NAME = {v: k for k, v in NAME_TO_PROPERTY.items()}
1941
1942    # CREATE property locations
1943    # Form: schema specified
1944    #   create [POST_CREATE]
1945    #     table a [POST_NAME]
1946    #     (b int) [POST_SCHEMA]
1947    #     with ([POST_WITH])
1948    #     index (b) [POST_INDEX]
1949    #
1950    # Form: alias selection
1951    #   create [POST_CREATE]
1952    #     table a [POST_NAME]
1953    #     as [POST_ALIAS] (select * from b) [POST_EXPRESSION]
1954    #     index (c) [POST_INDEX]
1955    class Location(AutoName):
1956        POST_CREATE = auto()
1957        POST_NAME = auto()
1958        POST_SCHEMA = auto()
1959        POST_WITH = auto()
1960        POST_ALIAS = auto()
1961        POST_EXPRESSION = auto()
1962        POST_INDEX = auto()
1963        UNSUPPORTED = auto()
1964
1965    @classmethod
1966    def from_dict(cls, properties_dict) -> Properties:
1967        expressions = []
1968        for key, value in properties_dict.items():
1969            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
1970            if property_cls:
1971                expressions.append(property_cls(this=convert(value)))
1972            else:
1973                expressions.append(Property(this=Literal.string(key), value=convert(value)))
1974
1975        return cls(expressions=expressions)
@classmethod
def from_dict(cls, properties_dict) -> sqlglot.expressions.Properties:
1965    @classmethod
1966    def from_dict(cls, properties_dict) -> Properties:
1967        expressions = []
1968        for key, value in properties_dict.items():
1969            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
1970            if property_cls:
1971                expressions.append(property_cls(this=convert(value)))
1972            else:
1973                expressions.append(Property(this=Literal.string(key), value=convert(value)))
1974
1975        return cls(expressions=expressions)
class Properties.Location(sqlglot.helper.AutoName):
1955    class Location(AutoName):
1956        POST_CREATE = auto()
1957        POST_NAME = auto()
1958        POST_SCHEMA = auto()
1959        POST_WITH = auto()
1960        POST_ALIAS = auto()
1961        POST_EXPRESSION = auto()
1962        POST_INDEX = auto()
1963        UNSUPPORTED = auto()

An enumeration.

POST_CREATE = <Location.POST_CREATE: 'POST_CREATE'>
POST_NAME = <Location.POST_NAME: 'POST_NAME'>
POST_SCHEMA = <Location.POST_SCHEMA: 'POST_SCHEMA'>
POST_WITH = <Location.POST_WITH: 'POST_WITH'>
POST_ALIAS = <Location.POST_ALIAS: 'POST_ALIAS'>
POST_EXPRESSION = <Location.POST_EXPRESSION: 'POST_EXPRESSION'>
POST_INDEX = <Location.POST_INDEX: 'POST_INDEX'>
UNSUPPORTED = <Location.UNSUPPORTED: 'UNSUPPORTED'>
Inherited Members
enum.Enum
name
value
class Qualify(Expression):
1978class Qualify(Expression):
1979    pass
class Return(Expression):
1983class Return(Expression):
1984    pass
class Reference(Expression):
1987class Reference(Expression):
1988    arg_types = {"this": True, "expressions": False, "options": False}
class Tuple(Expression):
1991class Tuple(Expression):
1992    arg_types = {"expressions": False}
1993
1994    def isin(
1995        self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy=True, **opts
1996    ) -> In:
1997        return In(
1998            this=_maybe_copy(self, copy),
1999            expressions=[convert(e, copy=copy) for e in expressions],
2000            query=maybe_parse(query, copy=copy, **opts) if query else None,
2001        )
def isin( self, *expressions: Any, query: Union[str, sqlglot.expressions.Expression, NoneType] = None, copy=True, **opts) -> sqlglot.expressions.In:
1994    def isin(
1995        self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy=True, **opts
1996    ) -> In:
1997        return In(
1998            this=_maybe_copy(self, copy),
1999            expressions=[convert(e, copy=copy) for e in expressions],
2000            query=maybe_parse(query, copy=copy, **opts) if query else None,
2001        )
class Subqueryable(Unionable):
2004class Subqueryable(Unionable):
2005    def subquery(self, alias=None, copy=True) -> Subquery:
2006        """
2007        Convert this expression to an aliased expression that can be used as a Subquery.
2008
2009        Example:
2010            >>> subquery = Select().select("x").from_("tbl").subquery()
2011            >>> Select().select("x").from_(subquery).sql()
2012            'SELECT x FROM (SELECT x FROM tbl)'
2013
2014        Args:
2015            alias (str | Identifier): an optional alias for the subquery
2016            copy (bool): if `False`, modify this expression instance in-place.
2017
2018        Returns:
2019            Alias: the subquery
2020        """
2021        instance = _maybe_copy(self, copy)
2022        return Subquery(
2023            this=instance,
2024            alias=TableAlias(this=to_identifier(alias)) if alias else None,
2025        )
2026
2027    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
2028        raise NotImplementedError
2029
2030    @property
2031    def ctes(self):
2032        with_ = self.args.get("with")
2033        if not with_:
2034            return []
2035        return with_.expressions
2036
2037    @property
2038    def selects(self):
2039        raise NotImplementedError("Subqueryable objects must implement `selects`")
2040
2041    @property
2042    def named_selects(self):
2043        raise NotImplementedError("Subqueryable objects must implement `named_selects`")
2044
2045    def with_(
2046        self,
2047        alias,
2048        as_,
2049        recursive=None,
2050        append=True,
2051        dialect=None,
2052        copy=True,
2053        **opts,
2054    ):
2055        """
2056        Append to or set the common table expressions.
2057
2058        Example:
2059            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
2060            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
2061
2062        Args:
2063            alias (str | Expression): the SQL code string to parse as the table name.
2064                If an `Expression` instance is passed, this is used as-is.
2065            as_ (str | Expression): the SQL code string to parse as the table expression.
2066                If an `Expression` instance is passed, it will be used as-is.
2067            recursive (bool): set the RECURSIVE part of the expression. Defaults to `False`.
2068            append (bool): if `True`, add to any existing expressions.
2069                Otherwise, this resets the expressions.
2070            dialect (str): the dialect used to parse the input expression.
2071            copy (bool): if `False`, modify this expression instance in-place.
2072            opts (kwargs): other options to use to parse the input expressions.
2073
2074        Returns:
2075            Select: the modified expression.
2076        """
2077        alias_expression = maybe_parse(
2078            alias,
2079            dialect=dialect,
2080            into=TableAlias,
2081            **opts,
2082        )
2083        as_expression = maybe_parse(
2084            as_,
2085            dialect=dialect,
2086            **opts,
2087        )
2088        cte = CTE(
2089            this=as_expression,
2090            alias=alias_expression,
2091        )
2092        return _apply_child_list_builder(
2093            cte,
2094            instance=self,
2095            arg="with",
2096            append=append,
2097            copy=copy,
2098            into=With,
2099            properties={"recursive": recursive or False},
2100        )
def subquery(self, alias=None, copy=True) -> sqlglot.expressions.Subquery:
2005    def subquery(self, alias=None, copy=True) -> Subquery:
2006        """
2007        Convert this expression to an aliased expression that can be used as a Subquery.
2008
2009        Example:
2010            >>> subquery = Select().select("x").from_("tbl").subquery()
2011            >>> Select().select("x").from_(subquery).sql()
2012            'SELECT x FROM (SELECT x FROM tbl)'
2013
2014        Args:
2015            alias (str | Identifier): an optional alias for the subquery
2016            copy (bool): if `False`, modify this expression instance in-place.
2017
2018        Returns:
2019            Alias: the subquery
2020        """
2021        instance = _maybe_copy(self, copy)
2022        return Subquery(
2023            this=instance,
2024            alias=TableAlias(this=to_identifier(alias)) if alias else None,
2025        )

Convert this expression to an aliased expression that can be used as a Subquery.

Example:
>>> subquery = Select().select("x").from_("tbl").subquery()
>>> Select().select("x").from_(subquery).sql()
'SELECT x FROM (SELECT x FROM tbl)'
Arguments:
  • alias (str | Identifier): an optional alias for the subquery
  • copy (bool): if False, modify this expression instance in-place.
Returns:

Alias: the subquery

def limit( self, expression, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2027    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
2028        raise NotImplementedError
def with_( self, alias, as_, recursive=None, append=True, dialect=None, copy=True, **opts):
2045    def with_(
2046        self,
2047        alias,
2048        as_,
2049        recursive=None,
2050        append=True,
2051        dialect=None,
2052        copy=True,
2053        **opts,
2054    ):
2055        """
2056        Append to or set the common table expressions.
2057
2058        Example:
2059            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
2060            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
2061
2062        Args:
2063            alias (str | Expression): the SQL code string to parse as the table name.
2064                If an `Expression` instance is passed, this is used as-is.
2065            as_ (str | Expression): the SQL code string to parse as the table expression.
2066                If an `Expression` instance is passed, it will be used as-is.
2067            recursive (bool): set the RECURSIVE part of the expression. Defaults to `False`.
2068            append (bool): if `True`, add to any existing expressions.
2069                Otherwise, this resets the expressions.
2070            dialect (str): the dialect used to parse the input expression.
2071            copy (bool): if `False`, modify this expression instance in-place.
2072            opts (kwargs): other options to use to parse the input expressions.
2073
2074        Returns:
2075            Select: the modified expression.
2076        """
2077        alias_expression = maybe_parse(
2078            alias,
2079            dialect=dialect,
2080            into=TableAlias,
2081            **opts,
2082        )
2083        as_expression = maybe_parse(
2084            as_,
2085            dialect=dialect,
2086            **opts,
2087        )
2088        cte = CTE(
2089            this=as_expression,
2090            alias=alias_expression,
2091        )
2092        return _apply_child_list_builder(
2093            cte,
2094            instance=self,
2095            arg="with",
2096            append=append,
2097            copy=copy,
2098            into=With,
2099            properties={"recursive": recursive or False},
2100        )

Append to or set the common table expressions.

Example:
>>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
Arguments:
  • alias (str | Expression): the SQL code string to parse as the table name. If an Expression instance is passed, this is used as-is.
  • as_ (str | Expression): the SQL code string to parse as the table expression. If an Expression instance is passed, it will be used as-is.
  • recursive (bool): set the RECURSIVE part of the expression. Defaults to False.
  • append (bool): if True, add to any existing expressions. Otherwise, this resets the expressions.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

class Table(Expression):
2124class Table(Expression):
2125    arg_types = {
2126        "this": True,
2127        "alias": False,
2128        "db": False,
2129        "catalog": False,
2130        "laterals": False,
2131        "joins": False,
2132        "pivots": False,
2133        "hints": False,
2134        "system_time": False,
2135    }
2136
2137    @property
2138    def db(self) -> str:
2139        return self.text("db")
2140
2141    @property
2142    def catalog(self) -> str:
2143        return self.text("catalog")
2144
2145    @property
2146    def parts(self) -> t.List[Identifier]:
2147        """Return the parts of a column in order catalog, db, table."""
2148        return [
2149            t.cast(Identifier, self.args[part])
2150            for part in ("catalog", "db", "this")
2151            if self.args.get(part)
2152        ]

Return the parts of a column in order catalog, db, table.

class SystemTime(Expression):
2156class SystemTime(Expression):
2157    arg_types = {
2158        "this": False,
2159        "expression": False,
2160        "kind": True,
2161    }
class Union(Subqueryable):
2164class Union(Subqueryable):
2165    arg_types = {
2166        "with": False,
2167        "this": True,
2168        "expression": True,
2169        "distinct": False,
2170        **QUERY_MODIFIERS,
2171    }
2172
2173    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
2174        """
2175        Set the LIMIT expression.
2176
2177        Example:
2178            >>> select("1").union(select("1")).limit(1).sql()
2179            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
2180
2181        Args:
2182            expression (str | int | Expression): the SQL code string to parse.
2183                This can also be an integer.
2184                If a `Limit` instance is passed, this is used as-is.
2185                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2186            dialect (str): the dialect used to parse the input expression.
2187            copy (bool): if `False`, modify this expression instance in-place.
2188            opts (kwargs): other options to use to parse the input expressions.
2189
2190        Returns:
2191            Select: The limited subqueryable.
2192        """
2193        return (
2194            select("*")
2195            .from_(self.subquery(alias="_l_0", copy=copy))
2196            .limit(expression, dialect=dialect, copy=False, **opts)
2197        )
2198
2199    def select(
2200        self,
2201        *expressions: ExpOrStr,
2202        append: bool = True,
2203        dialect: DialectType = None,
2204        copy: bool = True,
2205        **opts,
2206    ) -> Union:
2207        """Append to or set the SELECT of the union recursively.
2208
2209        Example:
2210            >>> from sqlglot import parse_one
2211            >>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
2212            'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
2213
2214        Args:
2215            *expressions: the SQL code strings to parse.
2216                If an `Expression` instance is passed, it will be used as-is.
2217            append: if `True`, add to any existing expressions.
2218                Otherwise, this resets the expressions.
2219            dialect: the dialect used to parse the input expressions.
2220            copy: if `False`, modify this expression instance in-place.
2221            opts: other options to use to parse the input expressions.
2222
2223        Returns:
2224            Union: the modified expression.
2225        """
2226        this = self.copy() if copy else self
2227        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
2228        this.expression.unnest().select(
2229            *expressions, append=append, dialect=dialect, copy=False, **opts
2230        )
2231        return this
2232
2233    @property
2234    def named_selects(self):
2235        return self.this.unnest().named_selects
2236
2237    @property
2238    def is_star(self) -> bool:
2239        return self.this.is_star or self.expression.is_star
2240
2241    @property
2242    def selects(self):
2243        return self.this.unnest().selects
2244
2245    @property
2246    def left(self):
2247        return self.this
2248
2249    @property
2250    def right(self):
2251        return self.expression
def limit( self, expression, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2173    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
2174        """
2175        Set the LIMIT expression.
2176
2177        Example:
2178            >>> select("1").union(select("1")).limit(1).sql()
2179            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
2180
2181        Args:
2182            expression (str | int | Expression): the SQL code string to parse.
2183                This can also be an integer.
2184                If a `Limit` instance is passed, this is used as-is.
2185                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2186            dialect (str): the dialect used to parse the input expression.
2187            copy (bool): if `False`, modify this expression instance in-place.
2188            opts (kwargs): other options to use to parse the input expressions.
2189
2190        Returns:
2191            Select: The limited subqueryable.
2192        """
2193        return (
2194            select("*")
2195            .from_(self.subquery(alias="_l_0", copy=copy))
2196            .limit(expression, dialect=dialect, copy=False, **opts)
2197        )

Set the LIMIT expression.

Example:
>>> select("1").union(select("1")).limit(1).sql()
'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
Arguments:
  • expression (str | int | Expression): the SQL code string to parse. This can also be an integer. If a Limit instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Limit.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: The limited subqueryable.

def select( self, *expressions: Union[str, sqlglot.expressions.Expression], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Union:
2199    def select(
2200        self,
2201        *expressions: ExpOrStr,
2202        append: bool = True,
2203        dialect: DialectType = None,
2204        copy: bool = True,
2205        **opts,
2206    ) -> Union:
2207        """Append to or set the SELECT of the union recursively.
2208
2209        Example:
2210            >>> from sqlglot import parse_one
2211            >>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
2212            'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
2213
2214        Args:
2215            *expressions: the SQL code strings to parse.
2216                If an `Expression` instance is passed, it will be used as-is.
2217            append: if `True`, add to any existing expressions.
2218                Otherwise, this resets the expressions.
2219            dialect: the dialect used to parse the input expressions.
2220            copy: if `False`, modify this expression instance in-place.
2221            opts: other options to use to parse the input expressions.
2222
2223        Returns:
2224            Union: the modified expression.
2225        """
2226        this = self.copy() if copy else self
2227        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
2228        this.expression.unnest().select(
2229            *expressions, append=append, dialect=dialect, copy=False, **opts
2230        )
2231        return this

Append to or set the SELECT of the union recursively.

Example:
>>> from sqlglot import parse_one
>>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • append: if True, add to any existing expressions. Otherwise, this resets the expressions.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Union: the modified expression.

is_star: bool

Checks whether an expression is a star.

class Except(Union):
2254class Except(Union):
2255    pass
class Intersect(Union):
2258class Intersect(Union):
2259    pass
class Unnest(UDTF):
2262class Unnest(UDTF):
2263    arg_types = {
2264        "expressions": True,
2265        "ordinality": False,
2266        "alias": False,
2267        "offset": False,
2268    }
class Update(Expression):
2271class Update(Expression):
2272    arg_types = {
2273        "with": False,
2274        "this": False,
2275        "expressions": True,
2276        "from": False,
2277        "where": False,
2278        "returning": False,
2279    }
class Values(UDTF):
2282class Values(UDTF):
2283    arg_types = {
2284        "expressions": True,
2285        "ordinality": False,
2286        "alias": False,
2287    }
class Var(Expression):
2290class Var(Expression):
2291    pass
class Schema(Expression):
2294class Schema(Expression):
2295    arg_types = {"this": False, "expressions": False}
class Lock(Expression):
2300class Lock(Expression):
2301    arg_types = {"update": True}
class Select(Subqueryable):
2304class Select(Subqueryable):
2305    arg_types = {
2306        "with": False,
2307        "kind": False,
2308        "expressions": False,
2309        "hint": False,
2310        "distinct": False,
2311        "struct": False,  # https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax#return_query_results_as_a_value_table
2312        "value": False,
2313        "into": False,
2314        "from": False,
2315        **QUERY_MODIFIERS,
2316    }
2317
2318    def from_(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2319        """
2320        Set the FROM expression.
2321
2322        Example:
2323            >>> Select().from_("tbl").select("x").sql()
2324            'SELECT x FROM tbl'
2325
2326        Args:
2327            *expressions (str | Expression): the SQL code strings to parse.
2328                If a `From` instance is passed, this is used as-is.
2329                If another `Expression` instance is passed, it will be wrapped in a `From`.
2330            append (bool): if `True`, add to any existing expressions.
2331                Otherwise, this flattens all the `From` expression into a single expression.
2332            dialect (str): the dialect used to parse the input expression.
2333            copy (bool): if `False`, modify this expression instance in-place.
2334            opts (kwargs): other options to use to parse the input expressions.
2335
2336        Returns:
2337            Select: the modified expression.
2338        """
2339        return _apply_child_list_builder(
2340            *expressions,
2341            instance=self,
2342            arg="from",
2343            append=append,
2344            copy=copy,
2345            prefix="FROM",
2346            into=From,
2347            dialect=dialect,
2348            **opts,
2349        )
2350
2351    def group_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2352        """
2353        Set the GROUP BY expression.
2354
2355        Example:
2356            >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
2357            'SELECT x, COUNT(1) FROM tbl GROUP BY x'
2358
2359        Args:
2360            *expressions (str | Expression): the SQL code strings to parse.
2361                If a `Group` instance is passed, this is used as-is.
2362                If another `Expression` instance is passed, it will be wrapped in a `Group`.
2363                If nothing is passed in then a group by is not applied to the expression
2364            append (bool): if `True`, add to any existing expressions.
2365                Otherwise, this flattens all the `Group` expression into a single expression.
2366            dialect (str): the dialect used to parse the input expression.
2367            copy (bool): if `False`, modify this expression instance in-place.
2368            opts (kwargs): other options to use to parse the input expressions.
2369
2370        Returns:
2371            Select: the modified expression.
2372        """
2373        if not expressions:
2374            return self if not copy else self.copy()
2375        return _apply_child_list_builder(
2376            *expressions,
2377            instance=self,
2378            arg="group",
2379            append=append,
2380            copy=copy,
2381            prefix="GROUP BY",
2382            into=Group,
2383            dialect=dialect,
2384            **opts,
2385        )
2386
2387    def order_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2388        """
2389        Set the ORDER BY expression.
2390
2391        Example:
2392            >>> Select().from_("tbl").select("x").order_by("x DESC").sql()
2393            'SELECT x FROM tbl ORDER BY x DESC'
2394
2395        Args:
2396            *expressions (str | Expression): the SQL code strings to parse.
2397                If a `Group` instance is passed, this is used as-is.
2398                If another `Expression` instance is passed, it will be wrapped in a `Order`.
2399            append (bool): if `True`, add to any existing expressions.
2400                Otherwise, this flattens all the `Order` expression into a single expression.
2401            dialect (str): the dialect used to parse the input expression.
2402            copy (bool): if `False`, modify this expression instance in-place.
2403            opts (kwargs): other options to use to parse the input expressions.
2404
2405        Returns:
2406            Select: the modified expression.
2407        """
2408        return _apply_child_list_builder(
2409            *expressions,
2410            instance=self,
2411            arg="order",
2412            append=append,
2413            copy=copy,
2414            prefix="ORDER BY",
2415            into=Order,
2416            dialect=dialect,
2417            **opts,
2418        )
2419
2420    def sort_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2421        """
2422        Set the SORT BY expression.
2423
2424        Example:
2425            >>> Select().from_("tbl").select("x").sort_by("x DESC").sql()
2426            'SELECT x FROM tbl SORT BY x DESC'
2427
2428        Args:
2429            *expressions (str | Expression): the SQL code strings to parse.
2430                If a `Group` instance is passed, this is used as-is.
2431                If another `Expression` instance is passed, it will be wrapped in a `SORT`.
2432            append (bool): if `True`, add to any existing expressions.
2433                Otherwise, this flattens all the `Order` expression into a single expression.
2434            dialect (str): the dialect used to parse the input expression.
2435            copy (bool): if `False`, modify this expression instance in-place.
2436            opts (kwargs): other options to use to parse the input expressions.
2437
2438        Returns:
2439            Select: the modified expression.
2440        """
2441        return _apply_child_list_builder(
2442            *expressions,
2443            instance=self,
2444            arg="sort",
2445            append=append,
2446            copy=copy,
2447            prefix="SORT BY",
2448            into=Sort,
2449            dialect=dialect,
2450            **opts,
2451        )
2452
2453    def cluster_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2454        """
2455        Set the CLUSTER BY expression.
2456
2457        Example:
2458            >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql()
2459            'SELECT x FROM tbl CLUSTER BY x DESC'
2460
2461        Args:
2462            *expressions (str | Expression): the SQL code strings to parse.
2463                If a `Group` instance is passed, this is used as-is.
2464                If another `Expression` instance is passed, it will be wrapped in a `Cluster`.
2465            append (bool): if `True`, add to any existing expressions.
2466                Otherwise, this flattens all the `Order` expression into a single expression.
2467            dialect (str): the dialect used to parse the input expression.
2468            copy (bool): if `False`, modify this expression instance in-place.
2469            opts (kwargs): other options to use to parse the input expressions.
2470
2471        Returns:
2472            Select: the modified expression.
2473        """
2474        return _apply_child_list_builder(
2475            *expressions,
2476            instance=self,
2477            arg="cluster",
2478            append=append,
2479            copy=copy,
2480            prefix="CLUSTER BY",
2481            into=Cluster,
2482            dialect=dialect,
2483            **opts,
2484        )
2485
2486    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
2487        """
2488        Set the LIMIT expression.
2489
2490        Example:
2491            >>> Select().from_("tbl").select("x").limit(10).sql()
2492            'SELECT x FROM tbl LIMIT 10'
2493
2494        Args:
2495            expression (str | int | Expression): the SQL code string to parse.
2496                This can also be an integer.
2497                If a `Limit` instance is passed, this is used as-is.
2498                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2499            dialect (str): the dialect used to parse the input expression.
2500            copy (bool): if `False`, modify this expression instance in-place.
2501            opts (kwargs): other options to use to parse the input expressions.
2502
2503        Returns:
2504            Select: the modified expression.
2505        """
2506        return _apply_builder(
2507            expression=expression,
2508            instance=self,
2509            arg="limit",
2510            into=Limit,
2511            prefix="LIMIT",
2512            dialect=dialect,
2513            copy=copy,
2514            **opts,
2515        )
2516
2517    def offset(self, expression, dialect=None, copy=True, **opts) -> Select:
2518        """
2519        Set the OFFSET expression.
2520
2521        Example:
2522            >>> Select().from_("tbl").select("x").offset(10).sql()
2523            'SELECT x FROM tbl OFFSET 10'
2524
2525        Args:
2526            expression (str | int | Expression): the SQL code string to parse.
2527                This can also be an integer.
2528                If a `Offset` instance is passed, this is used as-is.
2529                If another `Expression` instance is passed, it will be wrapped in a `Offset`.
2530            dialect (str): the dialect used to parse the input expression.
2531            copy (bool): if `False`, modify this expression instance in-place.
2532            opts (kwargs): other options to use to parse the input expressions.
2533
2534        Returns:
2535            Select: the modified expression.
2536        """
2537        return _apply_builder(
2538            expression=expression,
2539            instance=self,
2540            arg="offset",
2541            into=Offset,
2542            prefix="OFFSET",
2543            dialect=dialect,
2544            copy=copy,
2545            **opts,
2546        )
2547
2548    def select(
2549        self,
2550        *expressions: ExpOrStr,
2551        append: bool = True,
2552        dialect: DialectType = None,
2553        copy: bool = True,
2554        **opts,
2555    ) -> Select:
2556        """
2557        Append to or set the SELECT expressions.
2558
2559        Example:
2560            >>> Select().select("x", "y").sql()
2561            'SELECT x, y'
2562
2563        Args:
2564            *expressions: the SQL code strings to parse.
2565                If an `Expression` instance is passed, it will be used as-is.
2566            append: if `True`, add to any existing expressions.
2567                Otherwise, this resets the expressions.
2568            dialect: the dialect used to parse the input expressions.
2569            copy: if `False`, modify this expression instance in-place.
2570            opts: other options to use to parse the input expressions.
2571
2572        Returns:
2573            Select: the modified expression.
2574        """
2575        return _apply_list_builder(
2576            *expressions,
2577            instance=self,
2578            arg="expressions",
2579            append=append,
2580            dialect=dialect,
2581            copy=copy,
2582            **opts,
2583        )
2584
2585    def lateral(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2586        """
2587        Append to or set the LATERAL expressions.
2588
2589        Example:
2590            >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
2591            'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
2592
2593        Args:
2594            *expressions (str | Expression): the SQL code strings to parse.
2595                If an `Expression` instance is passed, it will be used as-is.
2596            append (bool): if `True`, add to any existing expressions.
2597                Otherwise, this resets the expressions.
2598            dialect (str): the dialect used to parse the input expressions.
2599            copy (bool): if `False`, modify this expression instance in-place.
2600            opts (kwargs): other options to use to parse the input expressions.
2601
2602        Returns:
2603            Select: the modified expression.
2604        """
2605        return _apply_list_builder(
2606            *expressions,
2607            instance=self,
2608            arg="laterals",
2609            append=append,
2610            into=Lateral,
2611            prefix="LATERAL VIEW",
2612            dialect=dialect,
2613            copy=copy,
2614            **opts,
2615        )
2616
2617    def join(
2618        self,
2619        expression,
2620        on=None,
2621        using=None,
2622        append=True,
2623        join_type=None,
2624        join_alias=None,
2625        dialect=None,
2626        copy=True,
2627        **opts,
2628    ) -> Select:
2629        """
2630        Append to or set the JOIN expressions.
2631
2632        Example:
2633            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
2634            'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
2635
2636            >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
2637            'SELECT 1 FROM a JOIN b USING (x, y, z)'
2638
2639            Use `join_type` to change the type of join:
2640
2641            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
2642            'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
2643
2644        Args:
2645            expression (str | Expression): the SQL code string to parse.
2646                If an `Expression` instance is passed, it will be used as-is.
2647            on (str | Expression): optionally specify the join "on" criteria as a SQL string.
2648                If an `Expression` instance is passed, it will be used as-is.
2649            using (str | Expression): optionally specify the join "using" criteria as a SQL string.
2650                If an `Expression` instance is passed, it will be used as-is.
2651            append (bool): if `True`, add to any existing expressions.
2652                Otherwise, this resets the expressions.
2653            join_type (str): If set, alter the parsed join type
2654            dialect (str): the dialect used to parse the input expressions.
2655            copy (bool): if `False`, modify this expression instance in-place.
2656            opts (kwargs): other options to use to parse the input expressions.
2657
2658        Returns:
2659            Select: the modified expression.
2660        """
2661        parse_args = {"dialect": dialect, **opts}
2662
2663        try:
2664            expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args)
2665        except ParseError:
2666            expression = maybe_parse(expression, into=(Join, Expression), **parse_args)
2667
2668        join = expression if isinstance(expression, Join) else Join(this=expression)
2669
2670        if isinstance(join.this, Select):
2671            join.this.replace(join.this.subquery())
2672
2673        if join_type:
2674            natural: t.Optional[Token]
2675            side: t.Optional[Token]
2676            kind: t.Optional[Token]
2677
2678            natural, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args)  # type: ignore
2679
2680            if natural:
2681                join.set("natural", True)
2682            if side:
2683                join.set("side", side.text)
2684            if kind:
2685                join.set("kind", kind.text)
2686
2687        if on:
2688            on = and_(*ensure_collection(on), dialect=dialect, copy=copy, **opts)
2689            join.set("on", on)
2690
2691        if using:
2692            join = _apply_list_builder(
2693                *ensure_collection(using),
2694                instance=join,
2695                arg="using",
2696                append=append,
2697                copy=copy,
2698                **opts,
2699            )
2700
2701        if join_alias:
2702            join.set("this", alias_(join.this, join_alias, table=True))
2703        return _apply_list_builder(
2704            join,
2705            instance=self,
2706            arg="joins",
2707            append=append,
2708            copy=copy,
2709            **opts,
2710        )
2711
2712    def where(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2713        """
2714        Append to or set the WHERE expressions.
2715
2716        Example:
2717            >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
2718            "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
2719
2720        Args:
2721            *expressions (str | Expression): the SQL code strings to parse.
2722                If an `Expression` instance is passed, it will be used as-is.
2723                Multiple expressions are combined with an AND operator.
2724            append (bool): if `True`, AND the new expressions to any existing expression.
2725                Otherwise, this resets the expression.
2726            dialect (str): the dialect used to parse the input expressions.
2727            copy (bool): if `False`, modify this expression instance in-place.
2728            opts (kwargs): other options to use to parse the input expressions.
2729
2730        Returns:
2731            Select: the modified expression.
2732        """
2733        return _apply_conjunction_builder(
2734            *expressions,
2735            instance=self,
2736            arg="where",
2737            append=append,
2738            into=Where,
2739            dialect=dialect,
2740            copy=copy,
2741            **opts,
2742        )
2743
2744    def having(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2745        """
2746        Append to or set the HAVING expressions.
2747
2748        Example:
2749            >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
2750            'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
2751
2752        Args:
2753            *expressions (str | Expression): the SQL code strings to parse.
2754                If an `Expression` instance is passed, it will be used as-is.
2755                Multiple expressions are combined with an AND operator.
2756            append (bool): if `True`, AND the new expressions to any existing expression.
2757                Otherwise, this resets the expression.
2758            dialect (str): the dialect used to parse the input expressions.
2759            copy (bool): if `False`, modify this expression instance in-place.
2760            opts (kwargs): other options to use to parse the input expressions.
2761
2762        Returns:
2763            Select: the modified expression.
2764        """
2765        return _apply_conjunction_builder(
2766            *expressions,
2767            instance=self,
2768            arg="having",
2769            append=append,
2770            into=Having,
2771            dialect=dialect,
2772            copy=copy,
2773            **opts,
2774        )
2775
2776    def window(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2777        return _apply_list_builder(
2778            *expressions,
2779            instance=self,
2780            arg="windows",
2781            append=append,
2782            into=Window,
2783            dialect=dialect,
2784            copy=copy,
2785            **opts,
2786        )
2787
2788    def qualify(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2789        return _apply_conjunction_builder(
2790            *expressions,
2791            instance=self,
2792            arg="qualify",
2793            append=append,
2794            into=Qualify,
2795            dialect=dialect,
2796            copy=copy,
2797            **opts,
2798        )
2799
2800    def distinct(self, *ons: ExpOrStr, distinct: bool = True, copy: bool = True) -> Select:
2801        """
2802        Set the OFFSET expression.
2803
2804        Example:
2805            >>> Select().from_("tbl").select("x").distinct().sql()
2806            'SELECT DISTINCT x FROM tbl'
2807
2808        Args:
2809            ons: the expressions to distinct on
2810            distinct: whether the Select should be distinct
2811            copy: if `False`, modify this expression instance in-place.
2812
2813        Returns:
2814            Select: the modified expression.
2815        """
2816        instance = _maybe_copy(self, copy)
2817        on = Tuple(expressions=[maybe_parse(on, copy=copy) for on in ons]) if ons else None
2818        instance.set("distinct", Distinct(on=on) if distinct else None)
2819        return instance
2820
2821    def ctas(self, table, properties=None, dialect=None, copy=True, **opts) -> Create:
2822        """
2823        Convert this expression to a CREATE TABLE AS statement.
2824
2825        Example:
2826            >>> Select().select("*").from_("tbl").ctas("x").sql()
2827            'CREATE TABLE x AS SELECT * FROM tbl'
2828
2829        Args:
2830            table (str | Expression): the SQL code string to parse as the table name.
2831                If another `Expression` instance is passed, it will be used as-is.
2832            properties (dict): an optional mapping of table properties
2833            dialect (str): the dialect used to parse the input table.
2834            copy (bool): if `False`, modify this expression instance in-place.
2835            opts (kwargs): other options to use to parse the input table.
2836
2837        Returns:
2838            Create: the CREATE TABLE AS expression
2839        """
2840        instance = _maybe_copy(self, copy)
2841        table_expression = maybe_parse(
2842            table,
2843            into=Table,
2844            dialect=dialect,
2845            **opts,
2846        )
2847        properties_expression = None
2848        if properties:
2849            properties_expression = Properties.from_dict(properties)
2850
2851        return Create(
2852            this=table_expression,
2853            kind="table",
2854            expression=instance,
2855            properties=properties_expression,
2856        )
2857
2858    def lock(self, update: bool = True, copy: bool = True) -> Select:
2859        """
2860        Set the locking read mode for this expression.
2861
2862        Examples:
2863            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
2864            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
2865
2866            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
2867            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
2868
2869        Args:
2870            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
2871            copy: if `False`, modify this expression instance in-place.
2872
2873        Returns:
2874            The modified expression.
2875        """
2876
2877        inst = _maybe_copy(self, copy)
2878        inst.set("lock", Lock(update=update))
2879
2880        return inst
2881
2882    @property
2883    def named_selects(self) -> t.List[str]:
2884        return [e.output_name for e in self.expressions if e.alias_or_name]
2885
2886    @property
2887    def is_star(self) -> bool:
2888        return any(expression.is_star for expression in self.expressions)
2889
2890    @property
2891    def selects(self) -> t.List[Expression]:
2892        return self.expressions
def from_( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2318    def from_(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2319        """
2320        Set the FROM expression.
2321
2322        Example:
2323            >>> Select().from_("tbl").select("x").sql()
2324            'SELECT x FROM tbl'
2325
2326        Args:
2327            *expressions (str | Expression): the SQL code strings to parse.
2328                If a `From` instance is passed, this is used as-is.
2329                If another `Expression` instance is passed, it will be wrapped in a `From`.
2330            append (bool): if `True`, add to any existing expressions.
2331                Otherwise, this flattens all the `From` expression into a single expression.
2332            dialect (str): the dialect used to parse the input expression.
2333            copy (bool): if `False`, modify this expression instance in-place.
2334            opts (kwargs): other options to use to parse the input expressions.
2335
2336        Returns:
2337            Select: the modified expression.
2338        """
2339        return _apply_child_list_builder(
2340            *expressions,
2341            instance=self,
2342            arg="from",
2343            append=append,
2344            copy=copy,
2345            prefix="FROM",
2346            into=From,
2347            dialect=dialect,
2348            **opts,
2349        )

Set the FROM expression.

Example:
>>> Select().from_("tbl").select("x").sql()
'SELECT x FROM tbl'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If a From instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a From.
  • append (bool): if True, add to any existing expressions. Otherwise, this flattens all the From expression into a single expression.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def group_by( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2351    def group_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2352        """
2353        Set the GROUP BY expression.
2354
2355        Example:
2356            >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
2357            'SELECT x, COUNT(1) FROM tbl GROUP BY x'
2358
2359        Args:
2360            *expressions (str | Expression): the SQL code strings to parse.
2361                If a `Group` instance is passed, this is used as-is.
2362                If another `Expression` instance is passed, it will be wrapped in a `Group`.
2363                If nothing is passed in then a group by is not applied to the expression
2364            append (bool): if `True`, add to any existing expressions.
2365                Otherwise, this flattens all the `Group` expression into a single expression.
2366            dialect (str): the dialect used to parse the input expression.
2367            copy (bool): if `False`, modify this expression instance in-place.
2368            opts (kwargs): other options to use to parse the input expressions.
2369
2370        Returns:
2371            Select: the modified expression.
2372        """
2373        if not expressions:
2374            return self if not copy else self.copy()
2375        return _apply_child_list_builder(
2376            *expressions,
2377            instance=self,
2378            arg="group",
2379            append=append,
2380            copy=copy,
2381            prefix="GROUP BY",
2382            into=Group,
2383            dialect=dialect,
2384            **opts,
2385        )

Set the GROUP BY expression.

Example:
>>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
'SELECT x, COUNT(1) FROM tbl GROUP BY x'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If a Group instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Group. If nothing is passed in then a group by is not applied to the expression
  • append (bool): if True, add to any existing expressions. Otherwise, this flattens all the Group expression into a single expression.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def order_by( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2387    def order_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2388        """
2389        Set the ORDER BY expression.
2390
2391        Example:
2392            >>> Select().from_("tbl").select("x").order_by("x DESC").sql()
2393            'SELECT x FROM tbl ORDER BY x DESC'
2394
2395        Args:
2396            *expressions (str | Expression): the SQL code strings to parse.
2397                If a `Group` instance is passed, this is used as-is.
2398                If another `Expression` instance is passed, it will be wrapped in a `Order`.
2399            append (bool): if `True`, add to any existing expressions.
2400                Otherwise, this flattens all the `Order` expression into a single expression.
2401            dialect (str): the dialect used to parse the input expression.
2402            copy (bool): if `False`, modify this expression instance in-place.
2403            opts (kwargs): other options to use to parse the input expressions.
2404
2405        Returns:
2406            Select: the modified expression.
2407        """
2408        return _apply_child_list_builder(
2409            *expressions,
2410            instance=self,
2411            arg="order",
2412            append=append,
2413            copy=copy,
2414            prefix="ORDER BY",
2415            into=Order,
2416            dialect=dialect,
2417            **opts,
2418        )

Set the ORDER BY expression.

Example:
>>> Select().from_("tbl").select("x").order_by("x DESC").sql()
'SELECT x FROM tbl ORDER BY x DESC'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If a Group instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Order.
  • append (bool): if True, add to any existing expressions. Otherwise, this flattens all the Order expression into a single expression.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def sort_by( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2420    def sort_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2421        """
2422        Set the SORT BY expression.
2423
2424        Example:
2425            >>> Select().from_("tbl").select("x").sort_by("x DESC").sql()
2426            'SELECT x FROM tbl SORT BY x DESC'
2427
2428        Args:
2429            *expressions (str | Expression): the SQL code strings to parse.
2430                If a `Group` instance is passed, this is used as-is.
2431                If another `Expression` instance is passed, it will be wrapped in a `SORT`.
2432            append (bool): if `True`, add to any existing expressions.
2433                Otherwise, this flattens all the `Order` expression into a single expression.
2434            dialect (str): the dialect used to parse the input expression.
2435            copy (bool): if `False`, modify this expression instance in-place.
2436            opts (kwargs): other options to use to parse the input expressions.
2437
2438        Returns:
2439            Select: the modified expression.
2440        """
2441        return _apply_child_list_builder(
2442            *expressions,
2443            instance=self,
2444            arg="sort",
2445            append=append,
2446            copy=copy,
2447            prefix="SORT BY",
2448            into=Sort,
2449            dialect=dialect,
2450            **opts,
2451        )

Set the SORT BY expression.

Example:
>>> Select().from_("tbl").select("x").sort_by("x DESC").sql()
'SELECT x FROM tbl SORT BY x DESC'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If a Group instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a SORT.
  • append (bool): if True, add to any existing expressions. Otherwise, this flattens all the Order expression into a single expression.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def cluster_by( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2453    def cluster_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2454        """
2455        Set the CLUSTER BY expression.
2456
2457        Example:
2458            >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql()
2459            'SELECT x FROM tbl CLUSTER BY x DESC'
2460
2461        Args:
2462            *expressions (str | Expression): the SQL code strings to parse.
2463                If a `Group` instance is passed, this is used as-is.
2464                If another `Expression` instance is passed, it will be wrapped in a `Cluster`.
2465            append (bool): if `True`, add to any existing expressions.
2466                Otherwise, this flattens all the `Order` expression into a single expression.
2467            dialect (str): the dialect used to parse the input expression.
2468            copy (bool): if `False`, modify this expression instance in-place.
2469            opts (kwargs): other options to use to parse the input expressions.
2470
2471        Returns:
2472            Select: the modified expression.
2473        """
2474        return _apply_child_list_builder(
2475            *expressions,
2476            instance=self,
2477            arg="cluster",
2478            append=append,
2479            copy=copy,
2480            prefix="CLUSTER BY",
2481            into=Cluster,
2482            dialect=dialect,
2483            **opts,
2484        )

Set the CLUSTER BY expression.

Example:
>>> Select().from_("tbl").select("x").cluster_by("x DESC").sql()
'SELECT x FROM tbl CLUSTER BY x DESC'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If a Group instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Cluster.
  • append (bool): if True, add to any existing expressions. Otherwise, this flattens all the Order expression into a single expression.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def limit( self, expression, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2486    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
2487        """
2488        Set the LIMIT expression.
2489
2490        Example:
2491            >>> Select().from_("tbl").select("x").limit(10).sql()
2492            'SELECT x FROM tbl LIMIT 10'
2493
2494        Args:
2495            expression (str | int | Expression): the SQL code string to parse.
2496                This can also be an integer.
2497                If a `Limit` instance is passed, this is used as-is.
2498                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2499            dialect (str): the dialect used to parse the input expression.
2500            copy (bool): if `False`, modify this expression instance in-place.
2501            opts (kwargs): other options to use to parse the input expressions.
2502
2503        Returns:
2504            Select: the modified expression.
2505        """
2506        return _apply_builder(
2507            expression=expression,
2508            instance=self,
2509            arg="limit",
2510            into=Limit,
2511            prefix="LIMIT",
2512            dialect=dialect,
2513            copy=copy,
2514            **opts,
2515        )

Set the LIMIT expression.

Example:
>>> Select().from_("tbl").select("x").limit(10).sql()
'SELECT x FROM tbl LIMIT 10'
Arguments:
  • expression (str | int | Expression): the SQL code string to parse. This can also be an integer. If a Limit instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Limit.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def offset( self, expression, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2517    def offset(self, expression, dialect=None, copy=True, **opts) -> Select:
2518        """
2519        Set the OFFSET expression.
2520
2521        Example:
2522            >>> Select().from_("tbl").select("x").offset(10).sql()
2523            'SELECT x FROM tbl OFFSET 10'
2524
2525        Args:
2526            expression (str | int | Expression): the SQL code string to parse.
2527                This can also be an integer.
2528                If a `Offset` instance is passed, this is used as-is.
2529                If another `Expression` instance is passed, it will be wrapped in a `Offset`.
2530            dialect (str): the dialect used to parse the input expression.
2531            copy (bool): if `False`, modify this expression instance in-place.
2532            opts (kwargs): other options to use to parse the input expressions.
2533
2534        Returns:
2535            Select: the modified expression.
2536        """
2537        return _apply_builder(
2538            expression=expression,
2539            instance=self,
2540            arg="offset",
2541            into=Offset,
2542            prefix="OFFSET",
2543            dialect=dialect,
2544            copy=copy,
2545            **opts,
2546        )

Set the OFFSET expression.

Example:
>>> Select().from_("tbl").select("x").offset(10).sql()
'SELECT x FROM tbl OFFSET 10'
Arguments:
  • expression (str | int | Expression): the SQL code string to parse. This can also be an integer. If a Offset instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Offset.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def select( self, *expressions: Union[str, sqlglot.expressions.Expression], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2548    def select(
2549        self,
2550        *expressions: ExpOrStr,
2551        append: bool = True,
2552        dialect: DialectType = None,
2553        copy: bool = True,
2554        **opts,
2555    ) -> Select:
2556        """
2557        Append to or set the SELECT expressions.
2558
2559        Example:
2560            >>> Select().select("x", "y").sql()
2561            'SELECT x, y'
2562
2563        Args:
2564            *expressions: the SQL code strings to parse.
2565                If an `Expression` instance is passed, it will be used as-is.
2566            append: if `True`, add to any existing expressions.
2567                Otherwise, this resets the expressions.
2568            dialect: the dialect used to parse the input expressions.
2569            copy: if `False`, modify this expression instance in-place.
2570            opts: other options to use to parse the input expressions.
2571
2572        Returns:
2573            Select: the modified expression.
2574        """
2575        return _apply_list_builder(
2576            *expressions,
2577            instance=self,
2578            arg="expressions",
2579            append=append,
2580            dialect=dialect,
2581            copy=copy,
2582            **opts,
2583        )

Append to or set the SELECT expressions.

Example:
>>> Select().select("x", "y").sql()
'SELECT x, y'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • append: if True, add to any existing expressions. Otherwise, this resets the expressions.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def lateral( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2585    def lateral(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2586        """
2587        Append to or set the LATERAL expressions.
2588
2589        Example:
2590            >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
2591            'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
2592
2593        Args:
2594            *expressions (str | Expression): the SQL code strings to parse.
2595                If an `Expression` instance is passed, it will be used as-is.
2596            append (bool): if `True`, add to any existing expressions.
2597                Otherwise, this resets the expressions.
2598            dialect (str): the dialect used to parse the input expressions.
2599            copy (bool): if `False`, modify this expression instance in-place.
2600            opts (kwargs): other options to use to parse the input expressions.
2601
2602        Returns:
2603            Select: the modified expression.
2604        """
2605        return _apply_list_builder(
2606            *expressions,
2607            instance=self,
2608            arg="laterals",
2609            append=append,
2610            into=Lateral,
2611            prefix="LATERAL VIEW",
2612            dialect=dialect,
2613            copy=copy,
2614            **opts,
2615        )

Append to or set the LATERAL expressions.

Example:
>>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • append (bool): if True, add to any existing expressions. Otherwise, this resets the expressions.
  • dialect (str): the dialect used to parse the input expressions.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def join( self, expression, on=None, using=None, append=True, join_type=None, join_alias=None, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2617    def join(
2618        self,
2619        expression,
2620        on=None,
2621        using=None,
2622        append=True,
2623        join_type=None,
2624        join_alias=None,
2625        dialect=None,
2626        copy=True,
2627        **opts,
2628    ) -> Select:
2629        """
2630        Append to or set the JOIN expressions.
2631
2632        Example:
2633            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
2634            'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
2635
2636            >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
2637            'SELECT 1 FROM a JOIN b USING (x, y, z)'
2638
2639            Use `join_type` to change the type of join:
2640
2641            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
2642            'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
2643
2644        Args:
2645            expression (str | Expression): the SQL code string to parse.
2646                If an `Expression` instance is passed, it will be used as-is.
2647            on (str | Expression): optionally specify the join "on" criteria as a SQL string.
2648                If an `Expression` instance is passed, it will be used as-is.
2649            using (str | Expression): optionally specify the join "using" criteria as a SQL string.
2650                If an `Expression` instance is passed, it will be used as-is.
2651            append (bool): if `True`, add to any existing expressions.
2652                Otherwise, this resets the expressions.
2653            join_type (str): If set, alter the parsed join type
2654            dialect (str): the dialect used to parse the input expressions.
2655            copy (bool): if `False`, modify this expression instance in-place.
2656            opts (kwargs): other options to use to parse the input expressions.
2657
2658        Returns:
2659            Select: the modified expression.
2660        """
2661        parse_args = {"dialect": dialect, **opts}
2662
2663        try:
2664            expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args)
2665        except ParseError:
2666            expression = maybe_parse(expression, into=(Join, Expression), **parse_args)
2667
2668        join = expression if isinstance(expression, Join) else Join(this=expression)
2669
2670        if isinstance(join.this, Select):
2671            join.this.replace(join.this.subquery())
2672
2673        if join_type:
2674            natural: t.Optional[Token]
2675            side: t.Optional[Token]
2676            kind: t.Optional[Token]
2677
2678            natural, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args)  # type: ignore
2679
2680            if natural:
2681                join.set("natural", True)
2682            if side:
2683                join.set("side", side.text)
2684            if kind:
2685                join.set("kind", kind.text)
2686
2687        if on:
2688            on = and_(*ensure_collection(on), dialect=dialect, copy=copy, **opts)
2689            join.set("on", on)
2690
2691        if using:
2692            join = _apply_list_builder(
2693                *ensure_collection(using),
2694                instance=join,
2695                arg="using",
2696                append=append,
2697                copy=copy,
2698                **opts,
2699            )
2700
2701        if join_alias:
2702            join.set("this", alias_(join.this, join_alias, table=True))
2703        return _apply_list_builder(
2704            join,
2705            instance=self,
2706            arg="joins",
2707            append=append,
2708            copy=copy,
2709            **opts,
2710        )

Append to or set the JOIN expressions.

Example:
>>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
>>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
'SELECT 1 FROM a JOIN b USING (x, y, z)'

Use join_type to change the type of join:

>>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
Arguments:
  • expression (str | Expression): the SQL code string to parse. If an Expression instance is passed, it will be used as-is.
  • on (str | Expression): optionally specify the join "on" criteria as a SQL string. If an Expression instance is passed, it will be used as-is.
  • using (str | Expression): optionally specify the join "using" criteria as a SQL string. If an Expression instance is passed, it will be used as-is.
  • append (bool): if True, add to any existing expressions. Otherwise, this resets the expressions.
  • join_type (str): If set, alter the parsed join type
  • dialect (str): the dialect used to parse the input expressions.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def where( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2712    def where(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2713        """
2714        Append to or set the WHERE expressions.
2715
2716        Example:
2717            >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
2718            "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
2719
2720        Args:
2721            *expressions (str | Expression): the SQL code strings to parse.
2722                If an `Expression` instance is passed, it will be used as-is.
2723                Multiple expressions are combined with an AND operator.
2724            append (bool): if `True`, AND the new expressions to any existing expression.
2725                Otherwise, this resets the expression.
2726            dialect (str): the dialect used to parse the input expressions.
2727            copy (bool): if `False`, modify this expression instance in-place.
2728            opts (kwargs): other options to use to parse the input expressions.
2729
2730        Returns:
2731            Select: the modified expression.
2732        """
2733        return _apply_conjunction_builder(
2734            *expressions,
2735            instance=self,
2736            arg="where",
2737            append=append,
2738            into=Where,
2739            dialect=dialect,
2740            copy=copy,
2741            **opts,
2742        )

Append to or set the WHERE expressions.

Example:
>>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
"SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator.
  • append (bool): if True, AND the new expressions to any existing expression. Otherwise, this resets the expression.
  • dialect (str): the dialect used to parse the input expressions.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def having( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2744    def having(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2745        """
2746        Append to or set the HAVING expressions.
2747
2748        Example:
2749            >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
2750            'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
2751
2752        Args:
2753            *expressions (str | Expression): the SQL code strings to parse.
2754                If an `Expression` instance is passed, it will be used as-is.
2755                Multiple expressions are combined with an AND operator.
2756            append (bool): if `True`, AND the new expressions to any existing expression.
2757                Otherwise, this resets the expression.
2758            dialect (str): the dialect used to parse the input expressions.
2759            copy (bool): if `False`, modify this expression instance in-place.
2760            opts (kwargs): other options to use to parse the input expressions.
2761
2762        Returns:
2763            Select: the modified expression.
2764        """
2765        return _apply_conjunction_builder(
2766            *expressions,
2767            instance=self,
2768            arg="having",
2769            append=append,
2770            into=Having,
2771            dialect=dialect,
2772            copy=copy,
2773            **opts,
2774        )

Append to or set the HAVING expressions.

Example:
>>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator.
  • append (bool): if True, AND the new expressions to any existing expression. Otherwise, this resets the expression.
  • dialect (str): the dialect used to parse the input expressions.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def window( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2776    def window(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2777        return _apply_list_builder(
2778            *expressions,
2779            instance=self,
2780            arg="windows",
2781            append=append,
2782            into=Window,
2783            dialect=dialect,
2784            copy=copy,
2785            **opts,
2786        )
def qualify( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2788    def qualify(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2789        return _apply_conjunction_builder(
2790            *expressions,
2791            instance=self,
2792            arg="qualify",
2793            append=append,
2794            into=Qualify,
2795            dialect=dialect,
2796            copy=copy,
2797            **opts,
2798        )
def distinct( self, *ons: Union[str, sqlglot.expressions.Expression], distinct: bool = True, copy: bool = True) -> sqlglot.expressions.Select:
2800    def distinct(self, *ons: ExpOrStr, distinct: bool = True, copy: bool = True) -> Select:
2801        """
2802        Set the OFFSET expression.
2803
2804        Example:
2805            >>> Select().from_("tbl").select("x").distinct().sql()
2806            'SELECT DISTINCT x FROM tbl'
2807
2808        Args:
2809            ons: the expressions to distinct on
2810            distinct: whether the Select should be distinct
2811            copy: if `False`, modify this expression instance in-place.
2812
2813        Returns:
2814            Select: the modified expression.
2815        """
2816        instance = _maybe_copy(self, copy)
2817        on = Tuple(expressions=[maybe_parse(on, copy=copy) for on in ons]) if ons else None
2818        instance.set("distinct", Distinct(on=on) if distinct else None)
2819        return instance

Set the OFFSET expression.

Example:
>>> Select().from_("tbl").select("x").distinct().sql()
'SELECT DISTINCT x FROM tbl'
Arguments:
  • ons: the expressions to distinct on
  • distinct: whether the Select should be distinct
  • copy: if False, modify this expression instance in-place.
Returns:

Select: the modified expression.

def ctas( self, table, properties=None, dialect=None, copy=True, **opts) -> sqlglot.expressions.Create:
2821    def ctas(self, table, properties=None, dialect=None, copy=True, **opts) -> Create:
2822        """
2823        Convert this expression to a CREATE TABLE AS statement.
2824
2825        Example:
2826            >>> Select().select("*").from_("tbl").ctas("x").sql()
2827            'CREATE TABLE x AS SELECT * FROM tbl'
2828
2829        Args:
2830            table (str | Expression): the SQL code string to parse as the table name.
2831                If another `Expression` instance is passed, it will be used as-is.
2832            properties (dict): an optional mapping of table properties
2833            dialect (str): the dialect used to parse the input table.
2834            copy (bool): if `False`, modify this expression instance in-place.
2835            opts (kwargs): other options to use to parse the input table.
2836
2837        Returns:
2838            Create: the CREATE TABLE AS expression
2839        """
2840        instance = _maybe_copy(self, copy)
2841        table_expression = maybe_parse(
2842            table,
2843            into=Table,
2844            dialect=dialect,
2845            **opts,
2846        )
2847        properties_expression = None
2848        if properties:
2849            properties_expression = Properties.from_dict(properties)
2850
2851        return Create(
2852            this=table_expression,
2853            kind="table",
2854            expression=instance,
2855            properties=properties_expression,
2856        )

Convert this expression to a CREATE TABLE AS statement.

Example:
>>> Select().select("*").from_("tbl").ctas("x").sql()
'CREATE TABLE x AS SELECT * FROM tbl'
Arguments:
  • table (str | Expression): the SQL code string to parse as the table name. If another Expression instance is passed, it will be used as-is.
  • properties (dict): an optional mapping of table properties
  • dialect (str): the dialect used to parse the input table.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input table.
Returns:

Create: the CREATE TABLE AS expression

def lock( self, update: bool = True, copy: bool = True) -> sqlglot.expressions.Select:
2858    def lock(self, update: bool = True, copy: bool = True) -> Select:
2859        """
2860        Set the locking read mode for this expression.
2861
2862        Examples:
2863            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
2864            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
2865
2866            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
2867            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
2868
2869        Args:
2870            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
2871            copy: if `False`, modify this expression instance in-place.
2872
2873        Returns:
2874            The modified expression.
2875        """
2876
2877        inst = _maybe_copy(self, copy)
2878        inst.set("lock", Lock(update=update))
2879
2880        return inst

Set the locking read mode for this expression.

Examples:
>>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
"SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
>>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
"SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
Arguments:
  • update: if True, the locking type will be FOR UPDATE, else it will be FOR SHARE.
  • copy: if False, modify this expression instance in-place.
Returns:

The modified expression.

is_star: bool

Checks whether an expression is a star.

class Subquery(DerivedTable, Unionable):
2895class Subquery(DerivedTable, Unionable):
2896    arg_types = {
2897        "this": True,
2898        "alias": False,
2899        "with": False,
2900        **QUERY_MODIFIERS,
2901    }
2902
2903    def unnest(self):
2904        """
2905        Returns the first non subquery.
2906        """
2907        expression = self
2908        while isinstance(expression, Subquery):
2909            expression = expression.this
2910        return expression
2911
2912    @property
2913    def is_star(self) -> bool:
2914        return self.this.is_star
2915
2916    @property
2917    def output_name(self):
2918        return self.alias
def unnest(self):
2903    def unnest(self):
2904        """
2905        Returns the first non subquery.
2906        """
2907        expression = self
2908        while isinstance(expression, Subquery):
2909            expression = expression.this
2910        return expression

Returns the first non subquery.

is_star: bool

Checks whether an expression is a star.

output_name

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
class TableSample(Expression):
2921class TableSample(Expression):
2922    arg_types = {
2923        "this": False,
2924        "method": False,
2925        "bucket_numerator": False,
2926        "bucket_denominator": False,
2927        "bucket_field": False,
2928        "percent": False,
2929        "rows": False,
2930        "size": False,
2931        "seed": False,
2932        "kind": False,
2933    }
class Tag(Expression):
2936class Tag(Expression):
2937    """Tags are used for generating arbitrary sql like SELECT <span>x</span>."""
2938
2939    arg_types = {
2940        "this": False,
2941        "prefix": False,
2942        "postfix": False,
2943    }

Tags are used for generating arbitrary sql like SELECT x.

class Pivot(Expression):
2946class Pivot(Expression):
2947    arg_types = {
2948        "this": False,
2949        "alias": False,
2950        "expressions": True,
2951        "field": True,
2952        "unpivot": True,
2953        "columns": False,
2954    }
class Window(Expression):
2957class Window(Expression):
2958    arg_types = {
2959        "this": True,
2960        "partition_by": False,
2961        "order": False,
2962        "spec": False,
2963        "alias": False,
2964        "over": False,
2965        "first": False,
2966    }
class WindowSpec(Expression):
2969class WindowSpec(Expression):
2970    arg_types = {
2971        "kind": False,
2972        "start": False,
2973        "start_side": False,
2974        "end": False,
2975        "end_side": False,
2976    }
class Where(Expression):
2979class Where(Expression):
2980    pass
class Star(Expression):
2983class Star(Expression):
2984    arg_types = {"except": False, "replace": False}
2985
2986    @property
2987    def name(self) -> str:
2988        return "*"
2989
2990    @property
2991    def output_name(self):
2992        return self.name
output_name

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
class Parameter(Expression):
2995class Parameter(Expression):
2996    arg_types = {"this": True, "wrapped": False}
class SessionParameter(Expression):
2999class SessionParameter(Expression):
3000    arg_types = {"this": True, "kind": False}
class Placeholder(Expression):
3003class Placeholder(Expression):
3004    arg_types = {"this": False}
class Null(Condition):
3007class Null(Condition):
3008    arg_types: t.Dict[str, t.Any] = {}
3009
3010    @property
3011    def name(self) -> str:
3012        return "NULL"
class Boolean(Condition):
3015class Boolean(Condition):
3016    pass
class DataTypeSize(Expression):
3019class DataTypeSize(Expression):
3020    arg_types = {"this": True, "expression": False}
class DataType(Expression):
3023class DataType(Expression):
3024    arg_types = {
3025        "this": True,
3026        "expressions": False,
3027        "nested": False,
3028        "values": False,
3029        "prefix": False,
3030    }
3031
3032    class Type(AutoName):
3033        CHAR = auto()
3034        NCHAR = auto()
3035        VARCHAR = auto()
3036        NVARCHAR = auto()
3037        TEXT = auto()
3038        MEDIUMTEXT = auto()
3039        LONGTEXT = auto()
3040        MEDIUMBLOB = auto()
3041        LONGBLOB = auto()
3042        BINARY = auto()
3043        VARBINARY = auto()
3044        INT = auto()
3045        UINT = auto()
3046        TINYINT = auto()
3047        UTINYINT = auto()
3048        SMALLINT = auto()
3049        USMALLINT = auto()
3050        BIGINT = auto()
3051        UBIGINT = auto()
3052        INT128 = auto()
3053        UINT128 = auto()
3054        INT256 = auto()
3055        UINT256 = auto()
3056        FLOAT = auto()
3057        DOUBLE = auto()
3058        DECIMAL = auto()
3059        BIGDECIMAL = auto()
3060        BIT = auto()
3061        BOOLEAN = auto()
3062        JSON = auto()
3063        JSONB = auto()
3064        INTERVAL = auto()
3065        TIME = auto()
3066        TIMESTAMP = auto()
3067        TIMESTAMPTZ = auto()
3068        TIMESTAMPLTZ = auto()
3069        DATE = auto()
3070        DATETIME = auto()
3071        DATETIME64 = auto()
3072        ARRAY = auto()
3073        MAP = auto()
3074        UUID = auto()
3075        GEOGRAPHY = auto()
3076        GEOMETRY = auto()
3077        STRUCT = auto()
3078        NULLABLE = auto()
3079        HLLSKETCH = auto()
3080        HSTORE = auto()
3081        SUPER = auto()
3082        SERIAL = auto()
3083        SMALLSERIAL = auto()
3084        BIGSERIAL = auto()
3085        XML = auto()
3086        UNIQUEIDENTIFIER = auto()
3087        MONEY = auto()
3088        SMALLMONEY = auto()
3089        ROWVERSION = auto()
3090        IMAGE = auto()
3091        VARIANT = auto()
3092        OBJECT = auto()
3093        INET = auto()
3094        NULL = auto()
3095        UNKNOWN = auto()  # Sentinel value, useful for type annotation
3096
3097    TEXT_TYPES = {
3098        Type.CHAR,
3099        Type.NCHAR,
3100        Type.VARCHAR,
3101        Type.NVARCHAR,
3102        Type.TEXT,
3103    }
3104
3105    INTEGER_TYPES = {
3106        Type.INT,
3107        Type.TINYINT,
3108        Type.SMALLINT,
3109        Type.BIGINT,
3110        Type.INT128,
3111        Type.INT256,
3112    }
3113
3114    FLOAT_TYPES = {
3115        Type.FLOAT,
3116        Type.DOUBLE,
3117    }
3118
3119    NUMERIC_TYPES = {*INTEGER_TYPES, *FLOAT_TYPES}
3120
3121    TEMPORAL_TYPES = {
3122        Type.TIMESTAMP,
3123        Type.TIMESTAMPTZ,
3124        Type.TIMESTAMPLTZ,
3125        Type.DATE,
3126        Type.DATETIME,
3127        Type.DATETIME64,
3128    }
3129
3130    @classmethod
3131    def build(
3132        cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs
3133    ) -> DataType:
3134        from sqlglot import parse_one
3135
3136        if isinstance(dtype, str):
3137            if dtype.upper() in cls.Type.__members__:
3138                data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[dtype.upper()])
3139            else:
3140                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
3141            if data_type_exp is None:
3142                raise ValueError(f"Unparsable data type value: {dtype}")
3143        elif isinstance(dtype, DataType.Type):
3144            data_type_exp = DataType(this=dtype)
3145        elif isinstance(dtype, DataType):
3146            return dtype
3147        else:
3148            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
3149        return DataType(**{**data_type_exp.args, **kwargs})
3150
3151    def is_type(self, dtype: DataType.Type) -> bool:
3152        return self.this == dtype
@classmethod
def build( cls, dtype: str | sqlglot.expressions.DataType | sqlglot.expressions.DataType.Type, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **kwargs) -> sqlglot.expressions.DataType:
3130    @classmethod
3131    def build(
3132        cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs
3133    ) -> DataType:
3134        from sqlglot import parse_one
3135
3136        if isinstance(dtype, str):
3137            if dtype.upper() in cls.Type.__members__:
3138                data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[dtype.upper()])
3139            else:
3140                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
3141            if data_type_exp is None:
3142                raise ValueError(f"Unparsable data type value: {dtype}")
3143        elif isinstance(dtype, DataType.Type):
3144            data_type_exp = DataType(this=dtype)
3145        elif isinstance(dtype, DataType):
3146            return dtype
3147        else:
3148            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
3149        return DataType(**{**data_type_exp.args, **kwargs})
def is_type(self, dtype: sqlglot.expressions.DataType.Type) -> bool:
3151    def is_type(self, dtype: DataType.Type) -> bool:
3152        return self.this == dtype
class DataType.Type(sqlglot.helper.AutoName):
3032    class Type(AutoName):
3033        CHAR = auto()
3034        NCHAR = auto()
3035        VARCHAR = auto()
3036        NVARCHAR = auto()
3037        TEXT = auto()
3038        MEDIUMTEXT = auto()
3039        LONGTEXT = auto()
3040        MEDIUMBLOB = auto()
3041        LONGBLOB = auto()
3042        BINARY = auto()
3043        VARBINARY = auto()
3044        INT = auto()
3045        UINT = auto()
3046        TINYINT = auto()
3047        UTINYINT = auto()
3048        SMALLINT = auto()
3049        USMALLINT = auto()
3050        BIGINT = auto()
3051        UBIGINT = auto()
3052        INT128 = auto()
3053        UINT128 = auto()
3054        INT256 = auto()
3055        UINT256 = auto()
3056        FLOAT = auto()
3057        DOUBLE = auto()
3058        DECIMAL = auto()
3059        BIGDECIMAL = auto()
3060        BIT = auto()
3061        BOOLEAN = auto()
3062        JSON = auto()
3063        JSONB = auto()
3064        INTERVAL = auto()
3065        TIME = auto()
3066        TIMESTAMP = auto()
3067        TIMESTAMPTZ = auto()
3068        TIMESTAMPLTZ = auto()
3069        DATE = auto()
3070        DATETIME = auto()
3071        DATETIME64 = auto()
3072        ARRAY = auto()
3073        MAP = auto()
3074        UUID = auto()
3075        GEOGRAPHY = auto()
3076        GEOMETRY = auto()
3077        STRUCT = auto()
3078        NULLABLE = auto()
3079        HLLSKETCH = auto()
3080        HSTORE = auto()
3081        SUPER = auto()
3082        SERIAL = auto()
3083        SMALLSERIAL = auto()
3084        BIGSERIAL = auto()
3085        XML = auto()
3086        UNIQUEIDENTIFIER = auto()
3087        MONEY = auto()
3088        SMALLMONEY = auto()
3089        ROWVERSION = auto()
3090        IMAGE = auto()
3091        VARIANT = auto()
3092        OBJECT = auto()
3093        INET = auto()
3094        NULL = auto()
3095        UNKNOWN = auto()  # Sentinel value, useful for type annotation

An enumeration.

CHAR = <Type.CHAR: 'CHAR'>
NCHAR = <Type.NCHAR: 'NCHAR'>
VARCHAR = <Type.VARCHAR: 'VARCHAR'>
NVARCHAR = <Type.NVARCHAR: 'NVARCHAR'>
TEXT = <Type.TEXT: 'TEXT'>
MEDIUMTEXT = <Type.MEDIUMTEXT: 'MEDIUMTEXT'>
LONGTEXT = <Type.LONGTEXT: 'LONGTEXT'>
MEDIUMBLOB = <Type.MEDIUMBLOB: 'MEDIUMBLOB'>
LONGBLOB = <Type.LONGBLOB: 'LONGBLOB'>
BINARY = <Type.BINARY: 'BINARY'>
VARBINARY = <Type.VARBINARY: 'VARBINARY'>
INT = <Type.INT: 'INT'>
UINT = <Type.UINT: 'UINT'>
TINYINT = <Type.TINYINT: 'TINYINT'>
UTINYINT = <Type.UTINYINT: 'UTINYINT'>
SMALLINT = <Type.SMALLINT: 'SMALLINT'>
USMALLINT = <Type.USMALLINT: 'USMALLINT'>
BIGINT = <Type.BIGINT: 'BIGINT'>
UBIGINT = <Type.UBIGINT: 'UBIGINT'>
INT128 = <Type.INT128: 'INT128'>
UINT128 = <Type.UINT128: 'UINT128'>
INT256 = <Type.INT256: 'INT256'>
UINT256 = <Type.UINT256: 'UINT256'>
FLOAT = <Type.FLOAT: 'FLOAT'>
DOUBLE = <Type.DOUBLE: 'DOUBLE'>
DECIMAL = <Type.DECIMAL: 'DECIMAL'>
BIGDECIMAL = <Type.BIGDECIMAL: 'BIGDECIMAL'>
BIT = <Type.BIT: 'BIT'>
BOOLEAN = <Type.BOOLEAN: 'BOOLEAN'>
JSON = <Type.JSON: 'JSON'>
JSONB = <Type.JSONB: 'JSONB'>
INTERVAL = <Type.INTERVAL: 'INTERVAL'>
TIME = <Type.TIME: 'TIME'>
TIMESTAMP = <Type.TIMESTAMP: 'TIMESTAMP'>
TIMESTAMPTZ = <Type.TIMESTAMPTZ: 'TIMESTAMPTZ'>
TIMESTAMPLTZ = <Type.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>
DATE = <Type.DATE: 'DATE'>
DATETIME = <Type.DATETIME: 'DATETIME'>
DATETIME64 = <Type.DATETIME64: 'DATETIME64'>
ARRAY = <Type.ARRAY: 'ARRAY'>
MAP = <Type.MAP: 'MAP'>
UUID = <Type.UUID: 'UUID'>
GEOGRAPHY = <Type.GEOGRAPHY: 'GEOGRAPHY'>
GEOMETRY = <Type.GEOMETRY: 'GEOMETRY'>
STRUCT = <Type.STRUCT: 'STRUCT'>
NULLABLE = <Type.NULLABLE: 'NULLABLE'>
HLLSKETCH = <Type.HLLSKETCH: 'HLLSKETCH'>
HSTORE = <Type.HSTORE: 'HSTORE'>
SUPER = <Type.SUPER: 'SUPER'>
SERIAL = <Type.SERIAL: 'SERIAL'>
SMALLSERIAL = <Type.SMALLSERIAL: 'SMALLSERIAL'>
BIGSERIAL = <Type.BIGSERIAL: 'BIGSERIAL'>
XML = <Type.XML: 'XML'>
UNIQUEIDENTIFIER = <Type.UNIQUEIDENTIFIER: 'UNIQUEIDENTIFIER'>
MONEY = <Type.MONEY: 'MONEY'>
SMALLMONEY = <Type.SMALLMONEY: 'SMALLMONEY'>
ROWVERSION = <Type.ROWVERSION: 'ROWVERSION'>
IMAGE = <Type.IMAGE: 'IMAGE'>
VARIANT = <Type.VARIANT: 'VARIANT'>
OBJECT = <Type.OBJECT: 'OBJECT'>
INET = <Type.INET: 'INET'>
NULL = <Type.NULL: 'NULL'>
UNKNOWN = <Type.UNKNOWN: 'UNKNOWN'>
Inherited Members
enum.Enum
name
value
class PseudoType(Expression):
3156class PseudoType(Expression):
3157    pass
class SubqueryPredicate(Predicate):
3161class SubqueryPredicate(Predicate):
3162    pass
class All(SubqueryPredicate):
3165class All(SubqueryPredicate):
3166    pass
class Any(SubqueryPredicate):
3169class Any(SubqueryPredicate):
3170    pass
class Exists(SubqueryPredicate):
3173class Exists(SubqueryPredicate):
3174    pass
class Command(Expression):
3179class Command(Expression):
3180    arg_types = {"this": True, "expression": False}
class Transaction(Expression):
3183class Transaction(Expression):
3184    arg_types = {"this": False, "modes": False}
class Commit(Expression):
3187class Commit(Expression):
3188    arg_types = {"chain": False}
class Rollback(Expression):
3191class Rollback(Expression):
3192    arg_types = {"savepoint": False}
class AlterTable(Expression):
3195class AlterTable(Expression):
3196    arg_types = {"this": True, "actions": True, "exists": False}
class AddConstraint(Expression):
3199class AddConstraint(Expression):
3200    arg_types = {"this": False, "expression": False, "enforced": False}
class DropPartition(Expression):
3203class DropPartition(Expression):
3204    arg_types = {"expressions": True, "exists": False}
class Binary(Condition):
3208class Binary(Condition):
3209    arg_types = {"this": True, "expression": True}
3210
3211    @property
3212    def left(self):
3213        return self.this
3214
3215    @property
3216    def right(self):
3217        return self.expression
class Add(Binary):
3220class Add(Binary):
3221    pass
class Connector(Binary):
3224class Connector(Binary):
3225    pass
class And(Connector):
3228class And(Connector):
3229    pass
class Or(Connector):
3232class Or(Connector):
3233    pass
class BitwiseAnd(Binary):
3236class BitwiseAnd(Binary):
3237    pass
class BitwiseLeftShift(Binary):
3240class BitwiseLeftShift(Binary):
3241    pass
class BitwiseOr(Binary):
3244class BitwiseOr(Binary):
3245    pass
class BitwiseRightShift(Binary):
3248class BitwiseRightShift(Binary):
3249    pass
class BitwiseXor(Binary):
3252class BitwiseXor(Binary):
3253    pass
class Div(Binary):
3256class Div(Binary):
3257    pass
class Overlaps(Binary):
3260class Overlaps(Binary):
3261    pass
class Dot(Binary):
3264class Dot(Binary):
3265    @property
3266    def name(self) -> str:
3267        return self.expression.name
3268
3269    @classmethod
3270    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3271        """Build a Dot object with a sequence of expressions."""
3272        if len(expressions) < 2:
3273            raise ValueError(f"Dot requires >= 2 expressions.")
3274
3275        a, b, *expressions = expressions
3276        dot = Dot(this=a, expression=b)
3277
3278        for expression in expressions:
3279            dot = Dot(this=dot, expression=expression)
3280
3281        return dot
@classmethod
def build( self, expressions: Sequence[sqlglot.expressions.Expression]) -> sqlglot.expressions.Dot:
3269    @classmethod
3270    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3271        """Build a Dot object with a sequence of expressions."""
3272        if len(expressions) < 2:
3273            raise ValueError(f"Dot requires >= 2 expressions.")
3274
3275        a, b, *expressions = expressions
3276        dot = Dot(this=a, expression=b)
3277
3278        for expression in expressions:
3279            dot = Dot(this=dot, expression=expression)
3280
3281        return dot

Build a Dot object with a sequence of expressions.

class DPipe(Binary):
3284class DPipe(Binary):
3285    pass
class EQ(Binary, Predicate):
3288class EQ(Binary, Predicate):
3289    pass
class NullSafeEQ(Binary, Predicate):
3292class NullSafeEQ(Binary, Predicate):
3293    pass
class NullSafeNEQ(Binary, Predicate):
3296class NullSafeNEQ(Binary, Predicate):
3297    pass
class Distance(Binary):
3300class Distance(Binary):
3301    pass
class Escape(Binary):
3304class Escape(Binary):
3305    pass
class Glob(Binary, Predicate):
3308class Glob(Binary, Predicate):
3309    pass
class GT(Binary, Predicate):
3312class GT(Binary, Predicate):
3313    pass
class GTE(Binary, Predicate):
3316class GTE(Binary, Predicate):
3317    pass
class ILike(Binary, Predicate):
3320class ILike(Binary, Predicate):
3321    pass
class ILikeAny(Binary, Predicate):
3324class ILikeAny(Binary, Predicate):
3325    pass
class IntDiv(Binary):
3328class IntDiv(Binary):
3329    pass
class Is(Binary, Predicate):
3332class Is(Binary, Predicate):
3333    pass
class Kwarg(Binary):
3336class Kwarg(Binary):
3337    """Kwarg in special functions like func(kwarg => y)."""

Kwarg in special functions like func(kwarg => y).

class Like(Binary, Predicate):
3340class Like(Binary, Predicate):
3341    pass
class LikeAny(Binary, Predicate):
3344class LikeAny(Binary, Predicate):
3345    pass
class LT(Binary, Predicate):
3348class LT(Binary, Predicate):
3349    pass
class LTE(Binary, Predicate):
3352class LTE(Binary, Predicate):
3353    pass
class Mod(Binary):
3356class Mod(Binary):
3357    pass
class Mul(Binary):
3360class Mul(Binary):
3361    pass
class NEQ(Binary, Predicate):
3364class NEQ(Binary, Predicate):
3365    pass
class SimilarTo(Binary, Predicate):
3368class SimilarTo(Binary, Predicate):
3369    pass
class Slice(Binary):
3372class Slice(Binary):
3373    arg_types = {"this": False, "expression": False}
class Sub(Binary):
3376class Sub(Binary):
3377    pass
class ArrayOverlaps(Binary):
3380class ArrayOverlaps(Binary):
3381    pass
class Unary(Condition):
3386class Unary(Condition):
3387    pass
class BitwiseNot(Unary):
3390class BitwiseNot(Unary):
3391    pass
class Not(Unary):
3394class Not(Unary):
3395    pass
class Paren(Unary):
3398class Paren(Unary):
3399    arg_types = {"this": True, "with": False}
class Neg(Unary):
3402class Neg(Unary):
3403    pass
class Alias(Expression):
3406class Alias(Expression):
3407    arg_types = {"this": True, "alias": False}
3408
3409    @property
3410    def output_name(self):
3411        return self.alias
output_name

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
class Aliases(Expression):
3414class Aliases(Expression):
3415    arg_types = {"this": True, "expressions": True}
3416
3417    @property
3418    def aliases(self):
3419        return self.expressions
class AtTimeZone(Expression):
3422class AtTimeZone(Expression):
3423    arg_types = {"this": True, "zone": True}
class Between(Predicate):
3426class Between(Predicate):
3427    arg_types = {"this": True, "low": True, "high": True}
class Bracket(Condition):
3430class Bracket(Condition):
3431    arg_types = {"this": True, "expressions": True}
class Distinct(Expression):
3434class Distinct(Expression):
3435    arg_types = {"expressions": False, "on": False}
class In(Predicate):
3438class In(Predicate):
3439    arg_types = {
3440        "this": True,
3441        "expressions": False,
3442        "query": False,
3443        "unnest": False,
3444        "field": False,
3445        "is_global": False,
3446    }
class TimeUnit(Expression):
3449class TimeUnit(Expression):
3450    """Automatically converts unit arg into a var."""
3451
3452    arg_types = {"unit": False}
3453
3454    def __init__(self, **args):
3455        unit = args.get("unit")
3456        if isinstance(unit, (Column, Literal)):
3457            args["unit"] = Var(this=unit.name)
3458        elif isinstance(unit, Week):
3459            unit.set("this", Var(this=unit.this.name))
3460        super().__init__(**args)

Automatically converts unit arg into a var.

TimeUnit(**args)
3454    def __init__(self, **args):
3455        unit = args.get("unit")
3456        if isinstance(unit, (Column, Literal)):
3457            args["unit"] = Var(this=unit.name)
3458        elif isinstance(unit, Week):
3459            unit.set("this", Var(this=unit.this.name))
3460        super().__init__(**args)
class Interval(TimeUnit):
3463class Interval(TimeUnit):
3464    arg_types = {"this": False, "unit": False}
class IgnoreNulls(Expression):
3467class IgnoreNulls(Expression):
3468    pass
class RespectNulls(Expression):
3471class RespectNulls(Expression):
3472    pass
class Func(Condition):
3476class Func(Condition):
3477    """
3478    The base class for all function expressions.
3479
3480    Attributes:
3481        is_var_len_args (bool): if set to True the last argument defined in arg_types will be
3482            treated as a variable length argument and the argument's value will be stored as a list.
3483        _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items)
3484            for this function expression. These values are used to map this node to a name during parsing
3485            as well as to provide the function's name during SQL string generation. By default the SQL
3486            name is set to the expression's class name transformed to snake case.
3487    """
3488
3489    is_var_len_args = False
3490
3491    @classmethod
3492    def from_arg_list(cls, args):
3493        if cls.is_var_len_args:
3494            all_arg_keys = list(cls.arg_types)
3495            # If this function supports variable length argument treat the last argument as such.
3496            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3497            num_non_var = len(non_var_len_arg_keys)
3498
3499            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3500            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3501        else:
3502            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3503
3504        return cls(**args_dict)
3505
3506    @classmethod
3507    def sql_names(cls):
3508        if cls is Func:
3509            raise NotImplementedError(
3510                "SQL name is only supported by concrete function implementations"
3511            )
3512        if "_sql_names" not in cls.__dict__:
3513            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3514        return cls._sql_names
3515
3516    @classmethod
3517    def sql_name(cls):
3518        return cls.sql_names()[0]
3519
3520    @classmethod
3521    def default_parser_mappings(cls):
3522        return {name: cls.from_arg_list for name in cls.sql_names()}

The base class for all function expressions.

Attributes:
  • is_var_len_args (bool): if set to True the last argument defined in arg_types will be treated as a variable length argument and the argument's value will be stored as a list.
  • _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items) for this function expression. These values are used to map this node to a name during parsing as well as to provide the function's name during SQL string generation. By default the SQL name is set to the expression's class name transformed to snake case.
@classmethod
def from_arg_list(cls, args):
3491    @classmethod
3492    def from_arg_list(cls, args):
3493        if cls.is_var_len_args:
3494            all_arg_keys = list(cls.arg_types)
3495            # If this function supports variable length argument treat the last argument as such.
3496            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3497            num_non_var = len(non_var_len_arg_keys)
3498
3499            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3500            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3501        else:
3502            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3503
3504        return cls(**args_dict)
@classmethod
def sql_names(cls):
3506    @classmethod
3507    def sql_names(cls):
3508        if cls is Func:
3509            raise NotImplementedError(
3510                "SQL name is only supported by concrete function implementations"
3511            )
3512        if "_sql_names" not in cls.__dict__:
3513            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3514        return cls._sql_names
@classmethod
def sql_name(cls):
3516    @classmethod
3517    def sql_name(cls):
3518        return cls.sql_names()[0]
@classmethod
def default_parser_mappings(cls):
3520    @classmethod
3521    def default_parser_mappings(cls):
3522        return {name: cls.from_arg_list for name in cls.sql_names()}
class AggFunc(Func):
3525class AggFunc(Func):
3526    pass
class Abs(Func):
3529class Abs(Func):
3530    pass
class Anonymous(Func):
3533class Anonymous(Func):
3534    arg_types = {"this": True, "expressions": False}
3535    is_var_len_args = True
class Hll(AggFunc):
3540class Hll(AggFunc):
3541    arg_types = {"this": True, "expressions": False}
3542    is_var_len_args = True
class ApproxDistinct(AggFunc):
3545class ApproxDistinct(AggFunc):
3546    arg_types = {"this": True, "accuracy": False}
class Array(Func):
3549class Array(Func):
3550    arg_types = {"expressions": False}
3551    is_var_len_args = True
class ToChar(Func):
3555class ToChar(Func):
3556    arg_types = {"this": True, "format": False}
class GenerateSeries(Func):
3559class GenerateSeries(Func):
3560    arg_types = {"start": True, "end": True, "step": False}
class ArrayAgg(AggFunc):
3563class ArrayAgg(AggFunc):
3564    pass
class ArrayAll(Func):
3567class ArrayAll(Func):
3568    arg_types = {"this": True, "expression": True}
class ArrayAny(Func):
3571class ArrayAny(Func):
3572    arg_types = {"this": True, "expression": True}
class ArrayConcat(Func):
3575class ArrayConcat(Func):
3576    arg_types = {"this": True, "expressions": False}
3577    is_var_len_args = True
class ArrayContains(Binary, Func):
3580class ArrayContains(Binary, Func):
3581    pass
class ArrayContained(Binary):
3584class ArrayContained(Binary):
3585    pass
class ArrayFilter(Func):
3588class ArrayFilter(Func):
3589    arg_types = {"this": True, "expression": True}
3590    _sql_names = ["FILTER", "ARRAY_FILTER"]
class ArrayJoin(Func):
3593class ArrayJoin(Func):
3594    arg_types = {"this": True, "expression": True, "null": False}
class ArraySize(Func):
3597class ArraySize(Func):
3598    arg_types = {"this": True, "expression": False}
class ArraySort(Func):
3601class ArraySort(Func):
3602    arg_types = {"this": True, "expression": False}
class ArraySum(Func):
3605class ArraySum(Func):
3606    pass
class ArrayUnionAgg(AggFunc):
3609class ArrayUnionAgg(AggFunc):
3610    pass
class Avg(AggFunc):
3613class Avg(AggFunc):
3614    pass
class AnyValue(AggFunc):
3617class AnyValue(AggFunc):
3618    pass
class Case(Func):
3621class Case(Func):
3622    arg_types = {"this": False, "ifs": True, "default": False}
3623
3624    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
3625        instance = _maybe_copy(self, copy)
3626        instance.append(
3627            "ifs",
3628            If(
3629                this=maybe_parse(condition, copy=copy, **opts),
3630                true=maybe_parse(then, copy=copy, **opts),
3631            ),
3632        )
3633        return instance
3634
3635    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
3636        instance = _maybe_copy(self, copy)
3637        instance.set("default", maybe_parse(condition, copy=copy, **opts))
3638        return instance
def when( self, condition: Union[str, sqlglot.expressions.Expression], then: Union[str, sqlglot.expressions.Expression], copy: bool = True, **opts) -> sqlglot.expressions.Case:
3624    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
3625        instance = _maybe_copy(self, copy)
3626        instance.append(
3627            "ifs",
3628            If(
3629                this=maybe_parse(condition, copy=copy, **opts),
3630                true=maybe_parse(then, copy=copy, **opts),
3631            ),
3632        )
3633        return instance
def else_( self, condition: Union[str, sqlglot.expressions.Expression], copy: bool = True, **opts) -> sqlglot.expressions.Case:
3635    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
3636        instance = _maybe_copy(self, copy)
3637        instance.set("default", maybe_parse(condition, copy=copy, **opts))
3638        return instance
class Cast(Func):
3641class Cast(Func):
3642    arg_types = {"this": True, "to": True}
3643
3644    @property
3645    def name(self) -> str:
3646        return self.this.name
3647
3648    @property
3649    def to(self):
3650        return self.args["to"]
3651
3652    @property
3653    def output_name(self):
3654        return self.name
3655
3656    def is_type(self, dtype: DataType.Type) -> bool:
3657        return self.to.is_type(dtype)
output_name

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
def is_type(self, dtype: sqlglot.expressions.DataType.Type) -> bool:
3656    def is_type(self, dtype: DataType.Type) -> bool:
3657        return self.to.is_type(dtype)
class Collate(Binary):
3660class Collate(Binary):
3661    pass
class TryCast(Cast):
3664class TryCast(Cast):
3665    pass
class Ceil(Func):
3668class Ceil(Func):
3669    arg_types = {"this": True, "decimals": False}
3670    _sql_names = ["CEIL", "CEILING"]
class Coalesce(Func):
3673class Coalesce(Func):
3674    arg_types = {"this": True, "expressions": False}
3675    is_var_len_args = True
class Concat(Func):
3678class Concat(Func):
3679    arg_types = {"expressions": True}
3680    is_var_len_args = True
class ConcatWs(Concat):
3683class ConcatWs(Concat):
3684    _sql_names = ["CONCAT_WS"]
class Count(AggFunc):
3687class Count(AggFunc):
3688    arg_types = {"this": False}
class CountIf(AggFunc):
3691class CountIf(AggFunc):
3692    pass
class CurrentDate(Func):
3695class CurrentDate(Func):
3696    arg_types = {"this": False}
class CurrentDatetime(Func):
3699class CurrentDatetime(Func):
3700    arg_types = {"this": False}
class CurrentTime(Func):
3703class CurrentTime(Func):
3704    arg_types = {"this": False}
class CurrentTimestamp(Func):
3707class CurrentTimestamp(Func):
3708    arg_types = {"this": False}
class CurrentUser(Func):
3711class CurrentUser(Func):
3712    arg_types = {"this": False}
class DateAdd(Func, TimeUnit):
3715class DateAdd(Func, TimeUnit):
3716    arg_types = {"this": True, "expression": True, "unit": False}
class DateSub(Func, TimeUnit):
3719class DateSub(Func, TimeUnit):
3720    arg_types = {"this": True, "expression": True, "unit": False}
class DateDiff(Func, TimeUnit):
3723class DateDiff(Func, TimeUnit):
3724    _sql_names = ["DATEDIFF", "DATE_DIFF"]
3725    arg_types = {"this": True, "expression": True, "unit": False}
class DateTrunc(Func):
3728class DateTrunc(Func):
3729    arg_types = {"unit": True, "this": True, "zone": False}
class DatetimeAdd(Func, TimeUnit):
3732class DatetimeAdd(Func, TimeUnit):
3733    arg_types = {"this": True, "expression": True, "unit": False}
class DatetimeSub(Func, TimeUnit):
3736class DatetimeSub(Func, TimeUnit):
3737    arg_types = {"this": True, "expression": True, "unit": False}
class DatetimeDiff(Func, TimeUnit):
3740class DatetimeDiff(Func, TimeUnit):
3741    arg_types = {"this": True, "expression": True, "unit": False}
class DatetimeTrunc(Func, TimeUnit):
3744class DatetimeTrunc(Func, TimeUnit):
3745    arg_types = {"this": True, "unit": True, "zone": False}
class DayOfWeek(Func):
3748class DayOfWeek(Func):
3749    _sql_names = ["DAY_OF_WEEK", "DAYOFWEEK"]
class DayOfMonth(Func):
3752class DayOfMonth(Func):
3753    _sql_names = ["DAY_OF_MONTH", "DAYOFMONTH"]
class DayOfYear(Func):
3756class DayOfYear(Func):
3757    _sql_names = ["DAY_OF_YEAR", "DAYOFYEAR"]
class WeekOfYear(Func):
3760class WeekOfYear(Func):
3761    _sql_names = ["WEEK_OF_YEAR", "WEEKOFYEAR"]
class LastDateOfMonth(Func):
3764class LastDateOfMonth(Func):
3765    pass
class Extract(Func):
3768class Extract(Func):
3769    arg_types = {"this": True, "expression": True}
class TimestampAdd(Func, TimeUnit):
3772class TimestampAdd(Func, TimeUnit):
3773    arg_types = {"this": True, "expression": True, "unit": False}
class TimestampSub(Func, TimeUnit):
3776class TimestampSub(Func, TimeUnit):
3777    arg_types = {"this": True, "expression": True, "unit": False}
class TimestampDiff(Func, TimeUnit):
3780class TimestampDiff(Func, TimeUnit):
3781    arg_types = {"this": True, "expression": True, "unit": False}
class TimestampTrunc(Func, TimeUnit):
3784class TimestampTrunc(Func, TimeUnit):
3785    arg_types = {"this": True, "unit": True, "zone": False}
class TimeAdd(Func, TimeUnit):
3788class TimeAdd(Func, TimeUnit):
3789    arg_types = {"this": True, "expression": True, "unit": False}
class TimeSub(Func, TimeUnit):
3792class TimeSub(Func, TimeUnit):
3793    arg_types = {"this": True, "expression": True, "unit": False}
class TimeDiff(Func, TimeUnit):
3796class TimeDiff(Func, TimeUnit):
3797    arg_types = {"this": True, "expression": True, "unit": False}
class TimeTrunc(Func, TimeUnit):
3800class TimeTrunc(Func, TimeUnit):
3801    arg_types = {"this": True, "unit": True, "zone": False}
class DateFromParts(Func):
3804class DateFromParts(Func):
3805    _sql_names = ["DATEFROMPARTS"]
3806    arg_types = {"year": True, "month": True, "day": True}
class DateStrToDate(Func):
3809class DateStrToDate(Func):
3810    pass
class DateToDateStr(Func):
3813class DateToDateStr(Func):
3814    pass
class DateToDi(Func):
3817class DateToDi(Func):
3818    pass
class Day(Func):
3821class Day(Func):
3822    pass
class Decode(Func):
3825class Decode(Func):
3826    arg_types = {"this": True, "charset": True, "replace": False}
class DiToDate(Func):
3829class DiToDate(Func):
3830    pass
class Encode(Func):
3833class Encode(Func):
3834    arg_types = {"this": True, "charset": True}
class Exp(Func):
3837class Exp(Func):
3838    pass
class Explode(Func):
3841class Explode(Func):
3842    pass
class ExponentialTimeDecayedAvg(AggFunc):
3845class ExponentialTimeDecayedAvg(AggFunc):
3846    arg_types = {"this": True, "time": False, "decay": False}
class Floor(Func):
3849class Floor(Func):
3850    arg_types = {"this": True, "decimals": False}
class FromBase64(Func):
3853class FromBase64(Func):
3854    pass
class ToBase64(Func):
3857class ToBase64(Func):
3858    pass
class Greatest(Func):
3861class Greatest(Func):
3862    arg_types = {"this": True, "expressions": False}
3863    is_var_len_args = True
class GroupConcat(Func):
3866class GroupConcat(Func):
3867    arg_types = {"this": True, "separator": False}
class GroupUniqArray(AggFunc):
3870class GroupUniqArray(AggFunc):
3871    arg_types = {"this": True, "size": False}
class Hex(Func):
3874class Hex(Func):
3875    pass
class Histogram(AggFunc):
3878class Histogram(AggFunc):
3879    arg_types = {"this": True, "bins": False}
class If(Func):
3882class If(Func):
3883    arg_types = {"this": True, "true": True, "false": False}
class IfNull(Func):
3886class IfNull(Func):
3887    arg_types = {"this": True, "expression": False}
3888    _sql_names = ["IFNULL", "NVL"]
class Initcap(Func):
3891class Initcap(Func):
3892    pass
class JSONKeyValue(Expression):
3895class JSONKeyValue(Expression):
3896    arg_types = {"this": True, "expression": True}
class JSONObject(Func):
3899class JSONObject(Func):
3900    arg_types = {
3901        "expressions": False,
3902        "null_handling": False,
3903        "unique_keys": False,
3904        "return_type": False,
3905        "format_json": False,
3906        "encoding": False,
3907    }
class OpenJSONColumnDef(Expression):
3910class OpenJSONColumnDef(Expression):
3911    arg_types = {"this": True, "kind": True, "path": False, "as_json": False}
class OpenJSON(Func):
3914class OpenJSON(Func):
3915    arg_types = {"this": True, "path": False, "expressions": False}
class JSONBContains(Binary):
3918class JSONBContains(Binary):
3919    _sql_names = ["JSONB_CONTAINS"]
class JSONExtract(Binary, Func):
3922class JSONExtract(Binary, Func):
3923    _sql_names = ["JSON_EXTRACT"]
class JSONExtractScalar(JSONExtract):
3926class JSONExtractScalar(JSONExtract):
3927    _sql_names = ["JSON_EXTRACT_SCALAR"]
class JSONBExtract(JSONExtract):
3930class JSONBExtract(JSONExtract):
3931    _sql_names = ["JSONB_EXTRACT"]
class JSONBExtractScalar(JSONExtract):
3934class JSONBExtractScalar(JSONExtract):
3935    _sql_names = ["JSONB_EXTRACT_SCALAR"]
class JSONFormat(Func):
3938class JSONFormat(Func):
3939    arg_types = {"this": False, "options": False}
3940    _sql_names = ["JSON_FORMAT"]
class Least(Func):
3943class Least(Func):
3944    arg_types = {"expressions": False}
3945    is_var_len_args = True
class Length(Func):
3948class Length(Func):
3949    pass
class Levenshtein(Func):
3952class Levenshtein(Func):
3953    arg_types = {
3954        "this": True,
3955        "expression": False,
3956        "ins_cost": False,
3957        "del_cost": False,
3958        "sub_cost": False,
3959    }
class Ln(Func):
3962class Ln(Func):
3963    pass
class Log(Func):
3966class Log(Func):
3967    arg_types = {"this": True, "expression": False}
class Log2(Func):
3970class Log2(Func):
3971    pass
class Log10(Func):
3974class Log10(Func):
3975    pass
class LogicalOr(AggFunc):
3978class LogicalOr(AggFunc):
3979    _sql_names = ["LOGICAL_OR", "BOOL_OR", "BOOLOR_AGG"]
class LogicalAnd(AggFunc):
3982class LogicalAnd(AggFunc):
3983    _sql_names = ["LOGICAL_AND", "BOOL_AND", "BOOLAND_AGG"]
class Lower(Func):
3986class Lower(Func):
3987    _sql_names = ["LOWER", "LCASE"]
class Map(Func):
3990class Map(Func):
3991    arg_types = {"keys": False, "values": False}
class StarMap(Func):
3994class StarMap(Func):
3995    pass
class VarMap(Func):
3998class VarMap(Func):
3999    arg_types = {"keys": True, "values": True}
4000    is_var_len_args = True
class MatchAgainst(Func):
4004class MatchAgainst(Func):
4005    arg_types = {"this": True, "expressions": True, "modifier": False}
class Max(AggFunc):
4008class Max(AggFunc):
4009    arg_types = {"this": True, "expressions": False}
4010    is_var_len_args = True
class MD5(Func):
4013class MD5(Func):
4014    _sql_names = ["MD5"]
class Min(AggFunc):
4017class Min(AggFunc):
4018    arg_types = {"this": True, "expressions": False}
4019    is_var_len_args = True
class Month(Func):
4022class Month(Func):
4023    pass
class Nvl2(Func):
4026class Nvl2(Func):
4027    arg_types = {"this": True, "true": True, "false": False}
class Posexplode(Func):
4030class Posexplode(Func):
4031    pass
class Pow(Binary, Func):
4034class Pow(Binary, Func):
4035    _sql_names = ["POWER", "POW"]
class PercentileCont(AggFunc):
4038class PercentileCont(AggFunc):
4039    arg_types = {"this": True, "expression": False}
class PercentileDisc(AggFunc):
4042class PercentileDisc(AggFunc):
4043    arg_types = {"this": True, "expression": False}
class Quantile(AggFunc):
4046class Quantile(AggFunc):
4047    arg_types = {"this": True, "quantile": True}
class Quantiles(AggFunc):
4052class Quantiles(AggFunc):
4053    arg_types = {"parameters": True, "expressions": True}
4054    is_var_len_args = True
class QuantileIf(AggFunc):
4057class QuantileIf(AggFunc):
4058    arg_types = {"parameters": True, "expressions": True}
class ApproxQuantile(Quantile):
4061class ApproxQuantile(Quantile):
4062    arg_types = {"this": True, "quantile": True, "accuracy": False, "weight": False}
class RangeN(Func):
4065class RangeN(Func):
4066    arg_types = {"this": True, "expressions": True, "each": False}
class ReadCSV(Func):
4069class ReadCSV(Func):
4070    _sql_names = ["READ_CSV"]
4071    is_var_len_args = True
4072    arg_types = {"this": True, "expressions": False}
class Reduce(Func):
4075class Reduce(Func):
4076    arg_types = {"this": True, "initial": True, "merge": True, "finish": False}
class RegexpExtract(Func):
4079class RegexpExtract(Func):
4080    arg_types = {
4081        "this": True,
4082        "expression": True,
4083        "position": False,
4084        "occurrence": False,
4085        "group": False,
4086    }
class RegexpLike(Func):
4089class RegexpLike(Func):
4090    arg_types = {"this": True, "expression": True, "flag": False}
class RegexpILike(Func):
4093class RegexpILike(Func):
4094    arg_types = {"this": True, "expression": True, "flag": False}
class RegexpSplit(Func):
4099class RegexpSplit(Func):
4100    arg_types = {"this": True, "expression": True, "limit": False}
class Repeat(Func):
4103class Repeat(Func):
4104    arg_types = {"this": True, "times": True}
class Round(Func):
4107class Round(Func):
4108    arg_types = {"this": True, "decimals": False}
class RowNumber(Func):
4111class RowNumber(Func):
4112    arg_types: t.Dict[str, t.Any] = {}
class SafeDivide(Func):
4115class SafeDivide(Func):
4116    arg_types = {"this": True, "expression": True}
class SetAgg(AggFunc):
4119class SetAgg(AggFunc):
4120    pass
class SHA(Func):
4123class SHA(Func):
4124    _sql_names = ["SHA", "SHA1"]
class SHA2(Func):
4127class SHA2(Func):
4128    _sql_names = ["SHA2"]
4129    arg_types = {"this": True, "length": False}
class SortArray(Func):
4132class SortArray(Func):
4133    arg_types = {"this": True, "asc": False}
class Split(Func):
4136class Split(Func):
4137    arg_types = {"this": True, "expression": True, "limit": False}
class Substring(Func):
4142class Substring(Func):
4143    arg_types = {"this": True, "start": False, "length": False}
class StandardHash(Func):
4146class StandardHash(Func):
4147    arg_types = {"this": True, "expression": False}
class StrPosition(Func):
4150class StrPosition(Func):
4151    arg_types = {
4152        "this": True,
4153        "substr": True,
4154        "position": False,
4155        "instance": False,
4156    }
class StrToDate(Func):
4159class StrToDate(Func):
4160    arg_types = {"this": True, "format": True}
class StrToTime(Func):
4163class StrToTime(Func):
4164    arg_types = {"this": True, "format": True}
class StrToUnix(Func):
4169class StrToUnix(Func):
4170    arg_types = {"this": False, "format": False}
class NumberToStr(Func):
4173class NumberToStr(Func):
4174    arg_types = {"this": True, "format": True}
class Struct(Func):
4177class Struct(Func):
4178    arg_types = {"expressions": True}
4179    is_var_len_args = True
class StructExtract(Func):
4182class StructExtract(Func):
4183    arg_types = {"this": True, "expression": True}
class Sum(AggFunc):
4186class Sum(AggFunc):
4187    pass
class Sqrt(Func):
4190class Sqrt(Func):
4191    pass
class Stddev(AggFunc):
4194class Stddev(AggFunc):
4195    pass
class StddevPop(AggFunc):
4198class StddevPop(AggFunc):
4199    pass
class StddevSamp(AggFunc):
4202class StddevSamp(AggFunc):
4203    pass
class TimeToStr(Func):
4206class TimeToStr(Func):
4207    arg_types = {"this": True, "format": True}
class TimeToTimeStr(Func):
4210class TimeToTimeStr(Func):
4211    pass
class TimeToUnix(Func):
4214class TimeToUnix(Func):
4215    pass
class TimeStrToDate(Func):
4218class TimeStrToDate(Func):
4219    pass
class TimeStrToTime(Func):
4222class TimeStrToTime(Func):
4223    pass
class TimeStrToUnix(Func):
4226class TimeStrToUnix(Func):
4227    pass
class Trim(Func):
4230class Trim(Func):
4231    arg_types = {
4232        "this": True,
4233        "expression": False,
4234        "position": False,
4235        "collation": False,
4236    }
class TsOrDsAdd(Func, TimeUnit):
4239class TsOrDsAdd(Func, TimeUnit):
4240    arg_types = {"this": True, "expression": True, "unit": False}
class TsOrDsToDateStr(Func):
4243class TsOrDsToDateStr(Func):
4244    pass
class TsOrDsToDate(Func):
4247class TsOrDsToDate(Func):
4248    arg_types = {"this": True, "format": False}
class TsOrDiToDi(Func):
4251class TsOrDiToDi(Func):
4252    pass
class Unhex(Func):
4255class Unhex(Func):
4256    pass
class UnixToStr(Func):
4259class UnixToStr(Func):
4260    arg_types = {"this": True, "format": False}
class UnixToTime(Func):
4265class UnixToTime(Func):
4266    arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False}
4267
4268    SECONDS = Literal.string("seconds")
4269    MILLIS = Literal.string("millis")
4270    MICROS = Literal.string("micros")
class UnixToTimeStr(Func):
4273class UnixToTimeStr(Func):
4274    pass
class Upper(Func):
4277class Upper(Func):
4278    _sql_names = ["UPPER", "UCASE"]
class Variance(AggFunc):
4281class Variance(AggFunc):
4282    _sql_names = ["VARIANCE", "VARIANCE_SAMP", "VAR_SAMP"]
class VariancePop(AggFunc):
4285class VariancePop(AggFunc):
4286    _sql_names = ["VARIANCE_POP", "VAR_POP"]
class Week(Func):
4289class Week(Func):
4290    arg_types = {"this": True, "mode": False}
class XMLTable(Func):
4293class XMLTable(Func):
4294    arg_types = {"this": True, "passing": False, "columns": False, "by_ref": False}
class Year(Func):
4297class Year(Func):
4298    pass
class Use(Expression):
4301class Use(Expression):
4302    arg_types = {"this": True, "kind": False}
class Merge(Expression):
4305class Merge(Expression):
4306    arg_types = {"this": True, "using": True, "on": True, "expressions": True}
class When(Func):
4309class When(Func):
4310    arg_types = {"matched": True, "source": False, "condition": False, "then": True}
class NextValueFor(Func):
4315class NextValueFor(Func):
4316    arg_types = {"this": True, "order": False}
def maybe_parse( sql_or_expression: Union[str, sqlglot.expressions.Expression], *, into: Union[str, Type[sqlglot.expressions.Expression], Collection[Union[str, Type[sqlglot.expressions.Expression]]], NoneType] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, prefix: Optional[str] = None, copy: bool = False, **opts) -> sqlglot.expressions.Expression:
4353def maybe_parse(
4354    sql_or_expression: ExpOrStr,
4355    *,
4356    into: t.Optional[IntoType] = None,
4357    dialect: DialectType = None,
4358    prefix: t.Optional[str] = None,
4359    copy: bool = False,
4360    **opts,
4361) -> Expression:
4362    """Gracefully handle a possible string or expression.
4363
4364    Example:
4365        >>> maybe_parse("1")
4366        (LITERAL this: 1, is_string: False)
4367        >>> maybe_parse(to_identifier("x"))
4368        (IDENTIFIER this: x, quoted: False)
4369
4370    Args:
4371        sql_or_expression: the SQL code string or an expression
4372        into: the SQLGlot Expression to parse into
4373        dialect: the dialect used to parse the input expressions (in the case that an
4374            input expression is a SQL string).
4375        prefix: a string to prefix the sql with before it gets parsed
4376            (automatically includes a space)
4377        copy: whether or not to copy the expression.
4378        **opts: other options to use to parse the input expressions (again, in the case
4379            that an input expression is a SQL string).
4380
4381    Returns:
4382        Expression: the parsed or given expression.
4383    """
4384    if isinstance(sql_or_expression, Expression):
4385        if copy:
4386            return sql_or_expression.copy()
4387        return sql_or_expression
4388
4389    import sqlglot
4390
4391    sql = str(sql_or_expression)
4392    if prefix:
4393        sql = f"{prefix} {sql}"
4394    return sqlglot.parse_one(sql, read=dialect, into=into, **opts)

Gracefully handle a possible string or expression.

Example:
>>> maybe_parse("1")
(LITERAL this: 1, is_string: False)
>>> maybe_parse(to_identifier("x"))
(IDENTIFIER this: x, quoted: False)
Arguments:
  • sql_or_expression: the SQL code string or an expression
  • into: the SQLGlot Expression to parse into
  • dialect: the dialect used to parse the input expressions (in the case that an input expression is a SQL string).
  • prefix: a string to prefix the sql with before it gets parsed (automatically includes a space)
  • copy: whether or not to copy the expression.
  • **opts: other options to use to parse the input expressions (again, in the case that an input expression is a SQL string).
Returns:

Expression: the parsed or given expression.

def union(left, right, distinct=True, dialect=None, **opts):
4542def union(left, right, distinct=True, dialect=None, **opts):
4543    """
4544    Initializes a syntax tree from one UNION expression.
4545
4546    Example:
4547        >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
4548        'SELECT * FROM foo UNION SELECT * FROM bla'
4549
4550    Args:
4551        left (str | Expression): the SQL code string corresponding to the left-hand side.
4552            If an `Expression` instance is passed, it will be used as-is.
4553        right (str | Expression): the SQL code string corresponding to the right-hand side.
4554            If an `Expression` instance is passed, it will be used as-is.
4555        distinct (bool): set the DISTINCT flag if and only if this is true.
4556        dialect (str): the dialect used to parse the input expression.
4557        opts (kwargs): other options to use to parse the input expressions.
4558    Returns:
4559        Union: the syntax tree for the UNION expression.
4560    """
4561    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4562    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4563
4564    return Union(this=left, expression=right, distinct=distinct)

Initializes a syntax tree from one UNION expression.

Example:
>>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
'SELECT * FROM foo UNION SELECT * FROM bla'
Arguments:
  • left (str | Expression): the SQL code string corresponding to the left-hand side. If an Expression instance is passed, it will be used as-is.
  • right (str | Expression): the SQL code string corresponding to the right-hand side. If an Expression instance is passed, it will be used as-is.
  • distinct (bool): set the DISTINCT flag if and only if this is true.
  • dialect (str): the dialect used to parse the input expression.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Union: the syntax tree for the UNION expression.

def intersect(left, right, distinct=True, dialect=None, **opts):
4567def intersect(left, right, distinct=True, dialect=None, **opts):
4568    """
4569    Initializes a syntax tree from one INTERSECT expression.
4570
4571    Example:
4572        >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
4573        'SELECT * FROM foo INTERSECT SELECT * FROM bla'
4574
4575    Args:
4576        left (str | Expression): the SQL code string corresponding to the left-hand side.
4577            If an `Expression` instance is passed, it will be used as-is.
4578        right (str | Expression): the SQL code string corresponding to the right-hand side.
4579            If an `Expression` instance is passed, it will be used as-is.
4580        distinct (bool): set the DISTINCT flag if and only if this is true.
4581        dialect (str): the dialect used to parse the input expression.
4582        opts (kwargs): other options to use to parse the input expressions.
4583    Returns:
4584        Intersect: the syntax tree for the INTERSECT expression.
4585    """
4586    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4587    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4588
4589    return Intersect(this=left, expression=right, distinct=distinct)

Initializes a syntax tree from one INTERSECT expression.

Example:
>>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
'SELECT * FROM foo INTERSECT SELECT * FROM bla'
Arguments:
  • left (str | Expression): the SQL code string corresponding to the left-hand side. If an Expression instance is passed, it will be used as-is.
  • right (str | Expression): the SQL code string corresponding to the right-hand side. If an Expression instance is passed, it will be used as-is.
  • distinct (bool): set the DISTINCT flag if and only if this is true.
  • dialect (str): the dialect used to parse the input expression.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Intersect: the syntax tree for the INTERSECT expression.

def except_(left, right, distinct=True, dialect=None, **opts):
4592def except_(left, right, distinct=True, dialect=None, **opts):
4593    """
4594    Initializes a syntax tree from one EXCEPT expression.
4595
4596    Example:
4597        >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
4598        'SELECT * FROM foo EXCEPT SELECT * FROM bla'
4599
4600    Args:
4601        left (str | Expression): the SQL code string corresponding to the left-hand side.
4602            If an `Expression` instance is passed, it will be used as-is.
4603        right (str | Expression): the SQL code string corresponding to the right-hand side.
4604            If an `Expression` instance is passed, it will be used as-is.
4605        distinct (bool): set the DISTINCT flag if and only if this is true.
4606        dialect (str): the dialect used to parse the input expression.
4607        opts (kwargs): other options to use to parse the input expressions.
4608    Returns:
4609        Except: the syntax tree for the EXCEPT statement.
4610    """
4611    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4612    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4613
4614    return Except(this=left, expression=right, distinct=distinct)

Initializes a syntax tree from one EXCEPT expression.

Example:
>>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
'SELECT * FROM foo EXCEPT SELECT * FROM bla'
Arguments:
  • left (str | Expression): the SQL code string corresponding to the left-hand side. If an Expression instance is passed, it will be used as-is.
  • right (str | Expression): the SQL code string corresponding to the right-hand side. If an Expression instance is passed, it will be used as-is.
  • distinct (bool): set the DISTINCT flag if and only if this is true.
  • dialect (str): the dialect used to parse the input expression.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Except: the syntax tree for the EXCEPT statement.

def select( *expressions: Union[str, sqlglot.expressions.Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Select:
4617def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
4618    """
4619    Initializes a syntax tree from one or multiple SELECT expressions.
4620
4621    Example:
4622        >>> select("col1", "col2").from_("tbl").sql()
4623        'SELECT col1, col2 FROM tbl'
4624
4625    Args:
4626        *expressions: the SQL code string to parse as the expressions of a
4627            SELECT statement. If an Expression instance is passed, this is used as-is.
4628        dialect: the dialect used to parse the input expressions (in the case that an
4629            input expression is a SQL string).
4630        **opts: other options to use to parse the input expressions (again, in the case
4631            that an input expression is a SQL string).
4632
4633    Returns:
4634        Select: the syntax tree for the SELECT statement.
4635    """
4636    return Select().select(*expressions, dialect=dialect, **opts)

Initializes a syntax tree from one or multiple SELECT expressions.

Example:
>>> select("col1", "col2").from_("tbl").sql()
'SELECT col1, col2 FROM tbl'
Arguments:
  • *expressions: the SQL code string to parse as the expressions of a SELECT statement. If an Expression instance is passed, this is used as-is.
  • dialect: the dialect used to parse the input expressions (in the case that an input expression is a SQL string).
  • **opts: other options to use to parse the input expressions (again, in the case that an input expression is a SQL string).
Returns:

Select: the syntax tree for the SELECT statement.

def from_(*expressions, dialect=None, **opts) -> sqlglot.expressions.Select:
4639def from_(*expressions, dialect=None, **opts) -> Select:
4640    """
4641    Initializes a syntax tree from a FROM expression.
4642
4643    Example:
4644        >>> from_("tbl").select("col1", "col2").sql()
4645        'SELECT col1, col2 FROM tbl'
4646
4647    Args:
4648        *expressions (str | Expression): the SQL code string to parse as the FROM expressions of a
4649            SELECT statement. If an Expression instance is passed, this is used as-is.
4650        dialect (str): the dialect used to parse the input expression (in the case that the
4651            input expression is a SQL string).
4652        **opts: other options to use to parse the input expressions (again, in the case
4653            that the input expression is a SQL string).
4654
4655    Returns:
4656        Select: the syntax tree for the SELECT statement.
4657    """
4658    return Select().from_(*expressions, dialect=dialect, **opts)

Initializes a syntax tree from a FROM expression.

Example:
>>> from_("tbl").select("col1", "col2").sql()
'SELECT col1, col2 FROM tbl'
Arguments:
  • *expressions (str | Expression): the SQL code string to parse as the FROM expressions of a SELECT statement. If an Expression instance is passed, this is used as-is.
  • dialect (str): the dialect used to parse the input expression (in the case that the input expression is a SQL string).
  • **opts: other options to use to parse the input expressions (again, in the case that the input expression is a SQL string).
Returns:

Select: the syntax tree for the SELECT statement.

def update( table: str | sqlglot.expressions.Table, properties: dict, where: Union[str, sqlglot.expressions.Expression, NoneType] = None, from_: Union[str, sqlglot.expressions.Expression, NoneType] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Update:
4661def update(
4662    table: str | Table,
4663    properties: dict,
4664    where: t.Optional[ExpOrStr] = None,
4665    from_: t.Optional[ExpOrStr] = None,
4666    dialect: DialectType = None,
4667    **opts,
4668) -> Update:
4669    """
4670    Creates an update statement.
4671
4672    Example:
4673        >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
4674        "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
4675
4676    Args:
4677        *properties: dictionary of properties to set which are
4678            auto converted to sql objects eg None -> NULL
4679        where: sql conditional parsed into a WHERE statement
4680        from_: sql statement parsed into a FROM statement
4681        dialect: the dialect used to parse the input expressions.
4682        **opts: other options to use to parse the input expressions.
4683
4684    Returns:
4685        Update: the syntax tree for the UPDATE statement.
4686    """
4687    update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect))
4688    update_expr.set(
4689        "expressions",
4690        [
4691            EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v))
4692            for k, v in properties.items()
4693        ],
4694    )
4695    if from_:
4696        update_expr.set(
4697            "from",
4698            maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts),
4699        )
4700    if isinstance(where, Condition):
4701        where = Where(this=where)
4702    if where:
4703        update_expr.set(
4704            "where",
4705            maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts),
4706        )
4707    return update_expr

Creates an update statement.

Example:
>>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
"UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
Arguments:
  • *properties: dictionary of properties to set which are auto converted to sql objects eg None -> NULL
  • where: sql conditional parsed into a WHERE statement
  • from_: sql statement parsed into a FROM statement
  • dialect: the dialect used to parse the input expressions.
  • **opts: other options to use to parse the input expressions.
Returns:

Update: the syntax tree for the UPDATE statement.

def delete( table: Union[str, sqlglot.expressions.Expression], where: Union[str, sqlglot.expressions.Expression, NoneType] = None, returning: Union[str, sqlglot.expressions.Expression, NoneType] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Delete:
4710def delete(
4711    table: ExpOrStr,
4712    where: t.Optional[ExpOrStr] = None,
4713    returning: t.Optional[ExpOrStr] = None,
4714    dialect: DialectType = None,
4715    **opts,
4716) -> Delete:
4717    """
4718    Builds a delete statement.
4719
4720    Example:
4721        >>> delete("my_table", where="id > 1").sql()
4722        'DELETE FROM my_table WHERE id > 1'
4723
4724    Args:
4725        where: sql conditional parsed into a WHERE statement
4726        returning: sql conditional parsed into a RETURNING statement
4727        dialect: the dialect used to parse the input expressions.
4728        **opts: other options to use to parse the input expressions.
4729
4730    Returns:
4731        Delete: the syntax tree for the DELETE statement.
4732    """
4733    delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts)
4734    if where:
4735        delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts)
4736    if returning:
4737        delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts)
4738    return delete_expr

Builds a delete statement.

Example:
>>> delete("my_table", where="id > 1").sql()
'DELETE FROM my_table WHERE id > 1'
Arguments:
  • where: sql conditional parsed into a WHERE statement
  • returning: sql conditional parsed into a RETURNING statement
  • dialect: the dialect used to parse the input expressions.
  • **opts: other options to use to parse the input expressions.
Returns:

Delete: the syntax tree for the DELETE statement.

def condition( expression, dialect=None, copy=True, **opts) -> sqlglot.expressions.Condition:
4741def condition(expression, dialect=None, copy=True, **opts) -> Condition:
4742    """
4743    Initialize a logical condition expression.
4744
4745    Example:
4746        >>> condition("x=1").sql()
4747        'x = 1'
4748
4749        This is helpful for composing larger logical syntax trees:
4750        >>> where = condition("x=1")
4751        >>> where = where.and_("y=1")
4752        >>> Select().from_("tbl").select("*").where(where).sql()
4753        'SELECT * FROM tbl WHERE x = 1 AND y = 1'
4754
4755    Args:
4756        *expression (str | Expression): the SQL code string to parse.
4757            If an Expression instance is passed, this is used as-is.
4758        dialect (str): the dialect used to parse the input expression (in the case that the
4759            input expression is a SQL string).
4760        copy (bool): Whether or not to copy `expression` (only applies to expressions).
4761        **opts: other options to use to parse the input expressions (again, in the case
4762            that the input expression is a SQL string).
4763
4764    Returns:
4765        Condition: the expression
4766    """
4767    return maybe_parse(  # type: ignore
4768        expression,
4769        into=Condition,
4770        dialect=dialect,
4771        copy=copy,
4772        **opts,
4773    )

Initialize a logical condition expression.

Example:
>>> condition("x=1").sql()
'x = 1'

This is helpful for composing larger logical syntax trees:

>>> where = condition("x=1")
>>> where = where.and_("y=1")
>>> Select().from_("tbl").select("*").where(where).sql()
'SELECT * FROM tbl WHERE x = 1 AND y = 1'
Arguments:
  • *expression (str | Expression): the SQL code string to parse. If an Expression instance is passed, this is used as-is.
  • dialect (str): the dialect used to parse the input expression (in the case that the input expression is a SQL string).
  • copy (bool): Whether or not to copy expression (only applies to expressions).
  • **opts: other options to use to parse the input expressions (again, in the case that the input expression is a SQL string).
Returns:

Condition: the expression

def and_(*expressions, dialect=None, copy=True, **opts) -> sqlglot.expressions.And:
4776def and_(*expressions, dialect=None, copy=True, **opts) -> And:
4777    """
4778    Combine multiple conditions with an AND logical operator.
4779
4780    Example:
4781        >>> and_("x=1", and_("y=1", "z=1")).sql()
4782        'x = 1 AND (y = 1 AND z = 1)'
4783
4784    Args:
4785        *expressions (str | Expression): the SQL code strings to parse.
4786            If an Expression instance is passed, this is used as-is.
4787        dialect (str): the dialect used to parse the input expression.
4788        copy (bool): whether or not to copy `expressions` (only applies to Expressions).
4789        **opts: other options to use to parse the input expressions.
4790
4791    Returns:
4792        And: the new condition
4793    """
4794    return _combine(expressions, And, dialect, copy=copy, **opts)

Combine multiple conditions with an AND logical operator.

Example:
>>> and_("x=1", and_("y=1", "z=1")).sql()
'x = 1 AND (y = 1 AND z = 1)'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): whether or not to copy expressions (only applies to Expressions).
  • **opts: other options to use to parse the input expressions.
Returns:

And: the new condition

def or_(*expressions, dialect=None, copy=True, **opts) -> sqlglot.expressions.Or:
4797def or_(*expressions, dialect=None, copy=True, **opts) -> Or:
4798    """
4799    Combine multiple conditions with an OR logical operator.
4800
4801    Example:
4802        >>> or_("x=1", or_("y=1", "z=1")).sql()
4803        'x = 1 OR (y = 1 OR z = 1)'
4804
4805    Args:
4806        *expressions (str | Expression): the SQL code strings to parse.
4807            If an Expression instance is passed, this is used as-is.
4808        dialect (str): the dialect used to parse the input expression.
4809        copy (bool): whether or not to copy `expressions` (only applies to Expressions).
4810        **opts: other options to use to parse the input expressions.
4811
4812    Returns:
4813        Or: the new condition
4814    """
4815    return _combine(expressions, Or, dialect, copy=copy, **opts)

Combine multiple conditions with an OR logical operator.

Example:
>>> or_("x=1", or_("y=1", "z=1")).sql()
'x = 1 OR (y = 1 OR z = 1)'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): whether or not to copy expressions (only applies to Expressions).
  • **opts: other options to use to parse the input expressions.
Returns:

Or: the new condition

def not_(expression, dialect=None, copy=True, **opts) -> sqlglot.expressions.Not:
4818def not_(expression, dialect=None, copy=True, **opts) -> Not:
4819    """
4820    Wrap a condition with a NOT operator.
4821
4822    Example:
4823        >>> not_("this_suit='black'").sql()
4824        "NOT this_suit = 'black'"
4825
4826    Args:
4827        expression (str | Expression): the SQL code strings to parse.
4828            If an Expression instance is passed, this is used as-is.
4829        dialect (str): the dialect used to parse the input expression.
4830        **opts: other options to use to parse the input expressions.
4831
4832    Returns:
4833        Not: the new condition
4834    """
4835    this = condition(
4836        expression,
4837        dialect=dialect,
4838        copy=copy,
4839        **opts,
4840    )
4841    return Not(this=_wrap(this, Connector))

Wrap a condition with a NOT operator.

Example:
>>> not_("this_suit='black'").sql()
"NOT this_suit = 'black'"
Arguments:
  • expression (str | Expression): the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
  • dialect (str): the dialect used to parse the input expression.
  • **opts: other options to use to parse the input expressions.
Returns:

Not: the new condition

def paren(expression, copy=True) -> sqlglot.expressions.Paren:
4844def paren(expression, copy=True) -> Paren:
4845    return Paren(this=_maybe_copy(expression, copy))
def to_identifier(name, quoted=None, copy=True):
4863def to_identifier(name, quoted=None, copy=True):
4864    """Builds an identifier.
4865
4866    Args:
4867        name: The name to turn into an identifier.
4868        quoted: Whether or not force quote the identifier.
4869        copy: Whether or not to copy a passed in Identefier node.
4870
4871    Returns:
4872        The identifier ast node.
4873    """
4874
4875    if name is None:
4876        return None
4877
4878    if isinstance(name, Identifier):
4879        identifier = _maybe_copy(name, copy)
4880    elif isinstance(name, str):
4881        identifier = Identifier(
4882            this=name,
4883            quoted=not SAFE_IDENTIFIER_RE.match(name) if quoted is None else quoted,
4884        )
4885    else:
4886        raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}")
4887    return identifier

Builds an identifier.

Arguments:
  • name: The name to turn into an identifier.
  • quoted: Whether or not force quote the identifier.
  • copy: Whether or not to copy a passed in Identefier node.
Returns:

The identifier ast node.

def to_interval( interval: str | sqlglot.expressions.Literal) -> sqlglot.expressions.Interval:
4893def to_interval(interval: str | Literal) -> Interval:
4894    """Builds an interval expression from a string like '1 day' or '5 months'."""
4895    if isinstance(interval, Literal):
4896        if not interval.is_string:
4897            raise ValueError("Invalid interval string.")
4898
4899        interval = interval.this
4900
4901    interval_parts = INTERVAL_STRING_RE.match(interval)  # type: ignore
4902
4903    if not interval_parts:
4904        raise ValueError("Invalid interval string.")
4905
4906    return Interval(
4907        this=Literal.string(interval_parts.group(1)),
4908        unit=Var(this=interval_parts.group(2)),
4909    )

Builds an interval expression from a string like '1 day' or '5 months'.

def to_table( sql_path: Union[str, sqlglot.expressions.Table, NoneType], **kwargs) -> Optional[sqlglot.expressions.Table]:
4922def to_table(sql_path: t.Optional[str | Table], **kwargs) -> t.Optional[Table]:
4923    """
4924    Create a table expression from a `[catalog].[schema].[table]` sql path. Catalog and schema are optional.
4925    If a table is passed in then that table is returned.
4926
4927    Args:
4928        sql_path: a `[catalog].[schema].[table]` string.
4929
4930    Returns:
4931        A table expression.
4932    """
4933    if sql_path is None or isinstance(sql_path, Table):
4934        return sql_path
4935    if not isinstance(sql_path, str):
4936        raise ValueError(f"Invalid type provided for a table: {type(sql_path)}")
4937
4938    catalog, db, table_name = (to_identifier(x) for x in split_num_words(sql_path, ".", 3))
4939    return Table(this=table_name, db=db, catalog=catalog, **kwargs)

Create a table expression from a [catalog].[schema].[table] sql path. Catalog and schema are optional. If a table is passed in then that table is returned.

Arguments:
  • sql_path: a [catalog].[schema].[table] string.
Returns:

A table expression.

def to_column( sql_path: str | sqlglot.expressions.Column, **kwargs) -> sqlglot.expressions.Column:
4942def to_column(sql_path: str | Column, **kwargs) -> Column:
4943    """
4944    Create a column from a `[table].[column]` sql path. Schema is optional.
4945
4946    If a column is passed in then that column is returned.
4947
4948    Args:
4949        sql_path: `[table].[column]` string
4950    Returns:
4951        Table: A column expression
4952    """
4953    if sql_path is None or isinstance(sql_path, Column):
4954        return sql_path
4955    if not isinstance(sql_path, str):
4956        raise ValueError(f"Invalid type provided for column: {type(sql_path)}")
4957    return column(*reversed(sql_path.split(".")), **kwargs)  # type: ignore

Create a column from a [table].[column] sql path. Schema is optional.

If a column is passed in then that column is returned.

Arguments:
  • sql_path: [table].[column] string
Returns:

Table: A column expression

def alias_( expression: Union[str, sqlglot.expressions.Expression], alias: str | sqlglot.expressions.Identifier, table: Union[bool, Sequence[str | sqlglot.expressions.Identifier]] = False, quoted: Optional[bool] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts):
4960def alias_(
4961    expression: ExpOrStr,
4962    alias: str | Identifier,
4963    table: bool | t.Sequence[str | Identifier] = False,
4964    quoted: t.Optional[bool] = None,
4965    dialect: DialectType = None,
4966    **opts,
4967):
4968    """Create an Alias expression.
4969
4970    Example:
4971        >>> alias_('foo', 'bar').sql()
4972        'foo AS bar'
4973
4974        >>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql()
4975        '(SELECT 1, 2) AS bar(a, b)'
4976
4977    Args:
4978        expression: the SQL code strings to parse.
4979            If an Expression instance is passed, this is used as-is.
4980        alias: the alias name to use. If the name has
4981            special characters it is quoted.
4982        table: Whether or not to create a table alias, can also be a list of columns.
4983        quoted: whether or not to quote the alias
4984        dialect: the dialect used to parse the input expression.
4985        **opts: other options to use to parse the input expressions.
4986
4987    Returns:
4988        Alias: the aliased expression
4989    """
4990    exp = maybe_parse(expression, dialect=dialect, **opts)
4991    alias = to_identifier(alias, quoted=quoted)
4992
4993    if table:
4994        table_alias = TableAlias(this=alias)
4995
4996        exp = exp.copy() if isinstance(expression, Expression) else exp
4997        exp.set("alias", table_alias)
4998
4999        if not isinstance(table, bool):
5000            for column in table:
5001                table_alias.append("columns", to_identifier(column, quoted=quoted))
5002
5003        return exp
5004
5005    # We don't set the "alias" arg for Window expressions, because that would add an IDENTIFIER node in
5006    # the AST, representing a "named_window" [1] construct (eg. bigquery). What we want is an ALIAS node
5007    # for the complete Window expression.
5008    #
5009    # [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/window-function-calls
5010
5011    if "alias" in exp.arg_types and not isinstance(exp, Window):
5012        exp = exp.copy()
5013        exp.set("alias", alias)
5014        return exp
5015    return Alias(this=exp, alias=alias)

Create an Alias expression.

Example:
>>> alias_('foo', 'bar').sql()
'foo AS bar'
>>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql()
'(SELECT 1, 2) AS bar(a, b)'
Arguments:
  • expression: the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
  • alias: the alias name to use. If the name has special characters it is quoted.
  • table: Whether or not to create a table alias, can also be a list of columns.
  • quoted: whether or not to quote the alias
  • dialect: the dialect used to parse the input expression.
  • **opts: other options to use to parse the input expressions.
Returns:

Alias: the aliased expression

def subquery(expression, alias=None, dialect=None, **opts):
5018def subquery(expression, alias=None, dialect=None, **opts):
5019    """
5020    Build a subquery expression.
5021
5022    Example:
5023        >>> subquery('select x from tbl', 'bar').select('x').sql()
5024        'SELECT x FROM (SELECT x FROM tbl) AS bar'
5025
5026    Args:
5027        expression (str | Expression): the SQL code strings to parse.
5028            If an Expression instance is passed, this is used as-is.
5029        alias (str | Expression): the alias name to use.
5030        dialect (str): the dialect used to parse the input expression.
5031        **opts: other options to use to parse the input expressions.
5032
5033    Returns:
5034        Select: a new select with the subquery expression included
5035    """
5036
5037    expression = maybe_parse(expression, dialect=dialect, **opts).subquery(alias)
5038    return Select().from_(expression, dialect=dialect, **opts)

Build a subquery expression.

Example:
>>> subquery('select x from tbl', 'bar').select('x').sql()
'SELECT x FROM (SELECT x FROM tbl) AS bar'
Arguments:
  • expression (str | Expression): the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
  • alias (str | Expression): the alias name to use.
  • dialect (str): the dialect used to parse the input expression.
  • **opts: other options to use to parse the input expressions.
Returns:

Select: a new select with the subquery expression included

def column( col: str | sqlglot.expressions.Identifier, table: Union[str, sqlglot.expressions.Identifier, NoneType] = None, db: Union[str, sqlglot.expressions.Identifier, NoneType] = None, catalog: Union[str, sqlglot.expressions.Identifier, NoneType] = None, quoted: Optional[bool] = None) -> sqlglot.expressions.Column:
5041def column(
5042    col: str | Identifier,
5043    table: t.Optional[str | Identifier] = None,
5044    db: t.Optional[str | Identifier] = None,
5045    catalog: t.Optional[str | Identifier] = None,
5046    quoted: t.Optional[bool] = None,
5047) -> Column:
5048    """
5049    Build a Column.
5050
5051    Args:
5052        col: column name
5053        table: table name
5054        db: db name
5055        catalog: catalog name
5056        quoted: whether or not to force quote each part
5057    Returns:
5058        Column: column instance
5059    """
5060    return Column(
5061        this=to_identifier(col, quoted=quoted),
5062        table=to_identifier(table, quoted=quoted),
5063        db=to_identifier(db, quoted=quoted),
5064        catalog=to_identifier(catalog, quoted=quoted),
5065    )

Build a Column.

Arguments:
  • col: column name
  • table: table name
  • db: db name
  • catalog: catalog name
  • quoted: whether or not to force quote each part
Returns:

Column: column instance

def cast( expression: Union[str, sqlglot.expressions.Expression], to: str | sqlglot.expressions.DataType | sqlglot.expressions.DataType.Type, **opts) -> sqlglot.expressions.Cast:
5068def cast(expression: ExpOrStr, to: str | DataType | DataType.Type, **opts) -> Cast:
5069    """Cast an expression to a data type.
5070
5071    Example:
5072        >>> cast('x + 1', 'int').sql()
5073        'CAST(x + 1 AS INT)'
5074
5075    Args:
5076        expression: The expression to cast.
5077        to: The datatype to cast to.
5078
5079    Returns:
5080        A cast node.
5081    """
5082    expression = maybe_parse(expression, **opts)
5083    return Cast(this=expression, to=DataType.build(to, **opts))

Cast an expression to a data type.

Example:
>>> cast('x + 1', 'int').sql()
'CAST(x + 1 AS INT)'
Arguments:
  • expression: The expression to cast.
  • to: The datatype to cast to.
Returns:

A cast node.

def table_( table, db=None, catalog=None, quoted=None, alias=None) -> sqlglot.expressions.Table:
5086def table_(table, db=None, catalog=None, quoted=None, alias=None) -> Table:
5087    """Build a Table.
5088
5089    Args:
5090        table (str | Expression): column name
5091        db (str | Expression): db name
5092        catalog (str | Expression): catalog name
5093
5094    Returns:
5095        Table: table instance
5096    """
5097    return Table(
5098        this=to_identifier(table, quoted=quoted),
5099        db=to_identifier(db, quoted=quoted),
5100        catalog=to_identifier(catalog, quoted=quoted),
5101        alias=TableAlias(this=to_identifier(alias)) if alias else None,
5102    )

Build a Table.

Arguments:
  • table (str | Expression): column name
  • db (str | Expression): db name
  • catalog (str | Expression): catalog name
Returns:

Table: table instance

def values( values: Iterable[Tuple[Any, ...]], alias: Optional[str] = None, columns: Union[Iterable[str], Dict[str, sqlglot.expressions.DataType], NoneType] = None) -> sqlglot.expressions.Values:
5105def values(
5106    values: t.Iterable[t.Tuple[t.Any, ...]],
5107    alias: t.Optional[str] = None,
5108    columns: t.Optional[t.Iterable[str] | t.Dict[str, DataType]] = None,
5109) -> Values:
5110    """Build VALUES statement.
5111
5112    Example:
5113        >>> values([(1, '2')]).sql()
5114        "VALUES (1, '2')"
5115
5116    Args:
5117        values: values statements that will be converted to SQL
5118        alias: optional alias
5119        columns: Optional list of ordered column names or ordered dictionary of column names to types.
5120         If either are provided then an alias is also required.
5121
5122    Returns:
5123        Values: the Values expression object
5124    """
5125    if columns and not alias:
5126        raise ValueError("Alias is required when providing columns")
5127
5128    return Values(
5129        expressions=[convert(tup) for tup in values],
5130        alias=(
5131            TableAlias(this=to_identifier(alias), columns=[to_identifier(x) for x in columns])
5132            if columns
5133            else (TableAlias(this=to_identifier(alias)) if alias else None)
5134        ),
5135    )

Build VALUES statement.

Example:
>>> values([(1, '2')]).sql()
"VALUES (1, '2')"
Arguments:
  • values: values statements that will be converted to SQL
  • alias: optional alias
  • columns: Optional list of ordered column names or ordered dictionary of column names to types. If either are provided then an alias is also required.
Returns:

Values: the Values expression object

def var( name: Union[str, sqlglot.expressions.Expression, NoneType]) -> sqlglot.expressions.Var:
5138def var(name: t.Optional[ExpOrStr]) -> Var:
5139    """Build a SQL variable.
5140
5141    Example:
5142        >>> repr(var('x'))
5143        '(VAR this: x)'
5144
5145        >>> repr(var(column('x', table='y')))
5146        '(VAR this: x)'
5147
5148    Args:
5149        name: The name of the var or an expression who's name will become the var.
5150
5151    Returns:
5152        The new variable node.
5153    """
5154    if not name:
5155        raise ValueError("Cannot convert empty name into var.")
5156
5157    if isinstance(name, Expression):
5158        name = name.name
5159    return Var(this=name)

Build a SQL variable.

Example:
>>> repr(var('x'))
'(VAR this: x)'
>>> repr(var(column('x', table='y')))
'(VAR this: x)'
Arguments:
  • name: The name of the var or an expression who's name will become the var.
Returns:

The new variable node.

def rename_table( old_name: str | sqlglot.expressions.Table, new_name: str | sqlglot.expressions.Table) -> sqlglot.expressions.AlterTable:
5162def rename_table(old_name: str | Table, new_name: str | Table) -> AlterTable:
5163    """Build ALTER TABLE... RENAME... expression
5164
5165    Args:
5166        old_name: The old name of the table
5167        new_name: The new name of the table
5168
5169    Returns:
5170        Alter table expression
5171    """
5172    old_table = to_table(old_name)
5173    new_table = to_table(new_name)
5174    return AlterTable(
5175        this=old_table,
5176        actions=[
5177            RenameTable(this=new_table),
5178        ],
5179    )

Build ALTER TABLE... RENAME... expression

Arguments:
  • old_name: The old name of the table
  • new_name: The new name of the table
Returns:

Alter table expression

def convert(value: Any, copy: bool = False) -> sqlglot.expressions.Expression:
5182def convert(value: t.Any, copy: bool = False) -> Expression:
5183    """Convert a python value into an expression object.
5184
5185    Raises an error if a conversion is not possible.
5186
5187    Args:
5188        value: A python object.
5189        copy: Whether or not to copy `value` (only applies to Expressions and collections).
5190
5191    Returns:
5192        Expression: the equivalent expression object.
5193    """
5194    if isinstance(value, Expression):
5195        return _maybe_copy(value, copy)
5196    if isinstance(value, str):
5197        return Literal.string(value)
5198    if isinstance(value, bool):
5199        return Boolean(this=value)
5200    if value is None or (isinstance(value, float) and math.isnan(value)):
5201        return NULL
5202    if isinstance(value, numbers.Number):
5203        return Literal.number(value)
5204    if isinstance(value, datetime.datetime):
5205        datetime_literal = Literal.string(
5206            (value if value.tzinfo else value.replace(tzinfo=datetime.timezone.utc)).isoformat()
5207        )
5208        return TimeStrToTime(this=datetime_literal)
5209    if isinstance(value, datetime.date):
5210        date_literal = Literal.string(value.strftime("%Y-%m-%d"))
5211        return DateStrToDate(this=date_literal)
5212    if isinstance(value, tuple):
5213        return Tuple(expressions=[convert(v, copy=copy) for v in value])
5214    if isinstance(value, list):
5215        return Array(expressions=[convert(v, copy=copy) for v in value])
5216    if isinstance(value, dict):
5217        return Map(
5218            keys=[convert(k, copy=copy) for k in value],
5219            values=[convert(v, copy=copy) for v in value.values()],
5220        )
5221    raise ValueError(f"Cannot convert {value}")

Convert a python value into an expression object.

Raises an error if a conversion is not possible.

Arguments:
  • value: A python object.
  • copy: Whether or not to copy value (only applies to Expressions and collections).
Returns:

Expression: the equivalent expression object.

def replace_children(expression, fun, *args, **kwargs):
5224def replace_children(expression, fun, *args, **kwargs):
5225    """
5226    Replace children of an expression with the result of a lambda fun(child) -> exp.
5227    """
5228    for k, v in expression.args.items():
5229        is_list_arg = type(v) is list
5230
5231        child_nodes = v if is_list_arg else [v]
5232        new_child_nodes = []
5233
5234        for cn in child_nodes:
5235            if isinstance(cn, Expression):
5236                for child_node in ensure_collection(fun(cn, *args, **kwargs)):
5237                    new_child_nodes.append(child_node)
5238                    child_node.parent = expression
5239                    child_node.arg_key = k
5240            else:
5241                new_child_nodes.append(cn)
5242
5243        expression.args[k] = new_child_nodes if is_list_arg else seq_get(new_child_nodes, 0)

Replace children of an expression with the result of a lambda fun(child) -> exp.

def column_table_names(expression):
5246def column_table_names(expression):
5247    """
5248    Return all table names referenced through columns in an expression.
5249
5250    Example:
5251        >>> import sqlglot
5252        >>> column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e"))
5253        ['c', 'a']
5254
5255    Args:
5256        expression (sqlglot.Expression): expression to find table names
5257
5258    Returns:
5259        list: A list of unique names
5260    """
5261    return list(dict.fromkeys(column.table for column in expression.find_all(Column)))

Return all table names referenced through columns in an expression.

Example:
>>> import sqlglot
>>> column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e"))
['c', 'a']
Arguments:
  • expression (sqlglot.Expression): expression to find table names
Returns:

list: A list of unique names

def table_name(table) -> str:
5264def table_name(table) -> str:
5265    """Get the full name of a table as a string.
5266
5267    Args:
5268        table (exp.Table | str): table expression node or string.
5269
5270    Examples:
5271        >>> from sqlglot import exp, parse_one
5272        >>> table_name(parse_one("select * from a.b.c").find(exp.Table))
5273        'a.b.c'
5274
5275    Returns:
5276        The table name.
5277    """
5278
5279    table = maybe_parse(table, into=Table)
5280
5281    if not table:
5282        raise ValueError(f"Cannot parse {table}")
5283
5284    return ".".join(
5285        part
5286        for part in (
5287            table.text("catalog"),
5288            table.text("db"),
5289            table.name,
5290        )
5291        if part
5292    )

Get the full name of a table as a string.

Arguments:
  • table (exp.Table | str): table expression node or string.
Examples:
>>> from sqlglot import exp, parse_one
>>> table_name(parse_one("select * from a.b.c").find(exp.Table))
'a.b.c'
Returns:

The table name.

def replace_tables(expression, mapping):
5295def replace_tables(expression, mapping):
5296    """Replace all tables in expression according to the mapping.
5297
5298    Args:
5299        expression (sqlglot.Expression): expression node to be transformed and replaced.
5300        mapping (Dict[str, str]): mapping of table names.
5301
5302    Examples:
5303        >>> from sqlglot import exp, parse_one
5304        >>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql()
5305        'SELECT * FROM c'
5306
5307    Returns:
5308        The mapped expression.
5309    """
5310
5311    def _replace_tables(node):
5312        if isinstance(node, Table):
5313            new_name = mapping.get(table_name(node))
5314            if new_name:
5315                return to_table(
5316                    new_name,
5317                    **{k: v for k, v in node.args.items() if k not in ("this", "db", "catalog")},
5318                )
5319        return node
5320
5321    return expression.transform(_replace_tables)

Replace all tables in expression according to the mapping.

Arguments:
  • expression (sqlglot.Expression): expression node to be transformed and replaced.
  • mapping (Dict[str, str]): mapping of table names.
Examples:
>>> from sqlglot import exp, parse_one
>>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql()
'SELECT * FROM c'
Returns:

The mapped expression.

def replace_placeholders(expression, *args, **kwargs):
5324def replace_placeholders(expression, *args, **kwargs):
5325    """Replace placeholders in an expression.
5326
5327    Args:
5328        expression (sqlglot.Expression): expression node to be transformed and replaced.
5329        args: positional names that will substitute unnamed placeholders in the given order.
5330        kwargs: keyword arguments that will substitute named placeholders.
5331
5332    Examples:
5333        >>> from sqlglot import exp, parse_one
5334        >>> replace_placeholders(
5335        ...     parse_one("select * from :tbl where ? = ?"),
5336        ...     exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo")
5337        ... ).sql()
5338        "SELECT * FROM foo WHERE str_col = 'b'"
5339
5340    Returns:
5341        The mapped expression.
5342    """
5343
5344    def _replace_placeholders(node, args, **kwargs):
5345        if isinstance(node, Placeholder):
5346            if node.name:
5347                new_name = kwargs.get(node.name)
5348                if new_name:
5349                    return convert(new_name)
5350            else:
5351                try:
5352                    return convert(next(args))
5353                except StopIteration:
5354                    pass
5355        return node
5356
5357    return expression.transform(_replace_placeholders, iter(args), **kwargs)

Replace placeholders in an expression.

Arguments:
  • expression (sqlglot.Expression): expression node to be transformed and replaced.
  • args: positional names that will substitute unnamed placeholders in the given order.
  • kwargs: keyword arguments that will substitute named placeholders.
Examples:
>>> from sqlglot import exp, parse_one
>>> replace_placeholders(
...     parse_one("select * from :tbl where ? = ?"),
...     exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo")
... ).sql()
"SELECT * FROM foo WHERE str_col = 'b'"
Returns:

The mapped expression.

def expand( expression: sqlglot.expressions.Expression, sources: Dict[str, sqlglot.expressions.Subqueryable], copy: bool = True) -> sqlglot.expressions.Expression:
5360def expand(
5361    expression: Expression, sources: t.Dict[str, Subqueryable], copy: bool = True
5362) -> Expression:
5363    """Transforms an expression by expanding all referenced sources into subqueries.
5364
5365    Examples:
5366        >>> from sqlglot import parse_one
5367        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql()
5368        'SELECT * FROM (SELECT * FROM y) AS z /* source: x */'
5369
5370        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y"), "y": parse_one("select * from z")}).sql()
5371        'SELECT * FROM (SELECT * FROM (SELECT * FROM z) AS y /* source: y */) AS z /* source: x */'
5372
5373    Args:
5374        expression: The expression to expand.
5375        sources: A dictionary of name to Subqueryables.
5376        copy: Whether or not to copy the expression during transformation. Defaults to True.
5377
5378    Returns:
5379        The transformed expression.
5380    """
5381
5382    def _expand(node: Expression):
5383        if isinstance(node, Table):
5384            name = table_name(node)
5385            source = sources.get(name)
5386            if source:
5387                subquery = source.subquery(node.alias or name)
5388                subquery.comments = [f"source: {name}"]
5389                return subquery.transform(_expand, copy=False)
5390        return node
5391
5392    return expression.transform(_expand, copy=copy)

Transforms an expression by expanding all referenced sources into subqueries.

Examples:
>>> from sqlglot import parse_one
>>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql()
'SELECT * FROM (SELECT * FROM y) AS z /* source: x */'
>>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y"), "y": parse_one("select * from z")}).sql()
'SELECT * FROM (SELECT * FROM (SELECT * FROM z) AS y /* source: y */) AS z /* source: x */'
Arguments:
  • expression: The expression to expand.
  • sources: A dictionary of name to Subqueryables.
  • copy: Whether or not to copy the expression during transformation. Defaults to True.
Returns:

The transformed expression.

def func( name: str, *args, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **kwargs) -> sqlglot.expressions.Func:
5395def func(name: str, *args, dialect: DialectType = None, **kwargs) -> Func:
5396    """
5397    Returns a Func expression.
5398
5399    Examples:
5400        >>> func("abs", 5).sql()
5401        'ABS(5)'
5402
5403        >>> func("cast", this=5, to=DataType.build("DOUBLE")).sql()
5404        'CAST(5 AS DOUBLE)'
5405
5406    Args:
5407        name: the name of the function to build.
5408        args: the args used to instantiate the function of interest.
5409        dialect: the source dialect.
5410        kwargs: the kwargs used to instantiate the function of interest.
5411
5412    Note:
5413        The arguments `args` and `kwargs` are mutually exclusive.
5414
5415    Returns:
5416        An instance of the function of interest, or an anonymous function, if `name` doesn't
5417        correspond to an existing `sqlglot.expressions.Func` class.
5418    """
5419    if args and kwargs:
5420        raise ValueError("Can't use both args and kwargs to instantiate a function.")
5421
5422    from sqlglot.dialects.dialect import Dialect
5423
5424    converted: t.List[Expression] = [maybe_parse(arg, dialect=dialect) for arg in args]
5425    kwargs = {key: maybe_parse(value, dialect=dialect) for key, value in kwargs.items()}
5426
5427    parser = Dialect.get_or_raise(dialect)().parser()
5428    from_args_list = parser.FUNCTIONS.get(name.upper())
5429
5430    if from_args_list:
5431        function = from_args_list(converted) if converted else from_args_list.__self__(**kwargs)  # type: ignore
5432    else:
5433        kwargs = kwargs or {"expressions": converted}
5434        function = Anonymous(this=name, **kwargs)
5435
5436    for error_message in function.error_messages(converted):
5437        raise ValueError(error_message)
5438
5439    return function

Returns a Func expression.

Examples:
>>> func("abs", 5).sql()
'ABS(5)'
>>> func("cast", this=5, to=DataType.build("DOUBLE")).sql()
'CAST(5 AS DOUBLE)'
Arguments:
  • name: the name of the function to build.
  • args: the args used to instantiate the function of interest.
  • dialect: the source dialect.
  • kwargs: the kwargs used to instantiate the function of interest.
Note:

The arguments args and kwargs are mutually exclusive.

Returns:

An instance of the function of interest, or an anonymous function, if name doesn't correspond to an existing sqlglot.expressions.Func class.

def true():
5442def true():
5443    """
5444    Returns a true Boolean expression.
5445    """
5446    return Boolean(this=True)

Returns a true Boolean expression.

def false():
5449def false():
5450    """
5451    Returns a false Boolean expression.
5452    """
5453    return Boolean(this=False)

Returns a false Boolean expression.

def null():
5456def null():
5457    """
5458    Returns a Null expression.
5459    """
5460    return Null()

Returns a Null expression.